简体   繁体   中英

Spring Boot MultipartFile upload getOriginalFileName different depending on browser

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.

EG: c:\\users\\daniel\\myfile.txt

If I upload a file from Google Chrome the value of uis.getOriginalFileName() is only the name of file.

EG: myfile.txt

How could I get only the name without the path for every browsers?

Is missing some @Bean to get that?

Thanks.

What javaLover suggested is not a good way to do it because it's platform dependent. For example, if your application runs on Linux and you upload a file from Windows, Path.getFileName() won't recognize backslashes that Windows uses as a name separator, and you will again get the full path instead of just the file name. That's why it's better to do it manually, something like

String fileName = uis.getOriginalFilename();
int startIndex = fileName.replaceAll("\\\\", "/").lastIndexOf("/");
fileName = fileName.substring(startIndex + 1);
myFile.setName(fileName);

Here we first replace back slashes with forward slashes to only care about one style of separators, and then find where the last separator is. Next we cut the string from the index that we found plus one to also get rid of the slash itself. Even if getOriginalFilename() only returns the file name without the path, this code will work because startIndex will be -1 and the resulting substring(0) call just won't have any effect.

Use apache commons IO. It handles a file in either Unix or Windows format.

org.apache.commons.io.FilenameUtils.getName(multipartFile.getOriginalFilename());

以这种方式修改 Java 代码中的以下行:

myFile.setName(java.nio.file.Paths.get(uis.getOriginalFilename()).getFileName());`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM