简体   繁体   English

Spring Boot MultipartFile 上传 getOriginalFileName 因浏览器而异

[英]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:我使用的是 spring boot 1.5.7-RELEASE 版本,我正在使用以下方法上传文件:

@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:我正在尝试将此文件上传到 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.前端是一个带有 Ajax 的简单表单 HTML。

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.当我从 Internet Explorer 或 Microsoft Edge 上传文件时,方法uis.getOriginalFilename()返回完整路径。

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

If I upload a file from Google Chrome the value of uis.getOriginalFileName() is only the name of file.如果我从 Google Chrome 上传文件,则uis.getOriginalFileName()值只是文件名。

EG: myfile.txt例如:myfile.txt

How could I get only the name without the path for every browsers?我怎么能只得到名称而没有每个浏览器的路径?

Is missing some @Bean to get that?是否缺少一些@Bean 来获得它?

Thanks.谢谢。

What javaLover suggested is not a good way to do it because it's platform dependent. javaLover 建议的不是一个好方法,因为它依赖于平台。 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.例如,如果您的应用程序在 Linux 上运行并且您从 Windows 上传文件, Path.getFileName()将无法识别 Windows 用作名称分隔符的反斜杠,您将再次获得完整路径而不仅仅是文件名。 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.接下来,我们将找到的索引中的字符串加上 1 以去除斜线本身。 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.即使getOriginalFilename()只返回不带路径的文件名,此代码也能工作,因为startIndex将为 -1 并且生成的substring(0)调用不会产生任何影响。

Use apache commons IO.使用 apache 公共 IO。 It handles a file in either Unix or Windows format.它处理 Unix 或 Windows 格式的文件。

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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