I am using spring boot 1.5.7-RELEASE version and I am uploading files with following method:
@Autowired private MyService mySerice;
@RequestMapping(value = "/uploadFile", method = { RequestMethod.POST }, produces = { MediaType.MULTIPART_FORM_DATA_VALUE,
MediaType.APPLICATION_FORM_URLENCODED_VALUE, MediaType.APPLICATION_JSON_VALUE })
public void upload(@RequestParam("file") MultipartFile uis, @RequestParam("user_id") String userId) {
MyFile myFile = new MyFile();
if (!uis.isEmpty()) {
myFile.setFile(uis.getBytes());
myFile.setName(uis.getOriginalFilename());
myFile.setUserId(userId);
myService.upload(myFile);
}
}
I am trying to upload this file to this table in MySQL:
CREATE TABLE `file_user` (
`id` int(5) UNSIGNED NOT NULL,
`user_id` bigint(20) UNSIGNED NOT NULL,
`file` mediumblob NOT NULL,
`name` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
ALTER TABLE `file_user` ADD PRIMARY KEY (`id`);
The front end is a simple form HTML with Ajax.
var fileInput = $("#file_form_post")[0].files[0];
var data = new FormData();
data.append("file", fileInput);
data.append("user_id", $("#txt_uid").val());
$.ajax({
url: 'mypage.com:9002/uploadFile',
type: 'POST',
data: data,
cache: false,
contentType: false,
processData: false,
headers: {Accept: "application/json"},
success: function (r) {
alert('Upload OK');
},
error: function (request, status, error) {
alert('Upload error');
}
});
When I upload a file from Internet Explorer or Microsoft Edge the method uis.getOriginalFilename() returns the complete path.
E.G.: c:\users\daniel\myfile.txt
If I upload a file from Google Chrome the value of uis.getOriginalFileName() is only the name of file.
E.G.: myfile.txt
How could I get only the name without the path for every browsers?
Is missing some @Bean to get that?
Thanks.
Use apache commons IO. It handles a file in either Unix or Windows format.
org.apache.commons.io.FilenameUtils.getName(multipartFile.getOriginalFilename());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With