源:https://blog.csdn.net/happy_cheng/article/details/54178392

1.现象是在spring-boot里加入commons-fileupload jar并且配置了mutilPart的bean,在upload的POST请求后,发现multipartRequest.getFiles=null,有点奇怪,查了文档资料才解决。

2.原因是:spring-boot自带的和Multipart产生冲突,如果同时使用了MultipartResolver 和ServletFileUpload,就会在iter.hasNext()返回false.然后整个循环就跳出去了。整个问题产生的原因是Spring框架先调用了MultipartResolver 来处理http multi-part的请求,这里http multipart的请求已经消耗掉,后面又交给ServletFileUpload,那么ServletFileUpload 就获取不到相应的multi-part请求。因此将multipartResolve配置去除,问题就解决了。

3、单文件的话只需要一个变量即,多文件上传的话就将MultipartFile改为数组,然后分别上传保存即可。

@RequestMapping(value="/multipleSave", method=RequestMethod.POST )
    public @ResponseBody String multipleSave(@RequestParam("file") MultipartFile[] files){
        String fileName = null;
        String msg = "";
        if (files != null && files.length >0) {
            for(int i =0 ;i< files.length; i++){
                try {
                    fileName = files[i].getOriginalFilename();
                    byte[] bytes = files[i].getBytes();
                    BufferedOutputStream buffStream = 
                            new BufferedOutputStream(new FileOutputStream(new File("/tmp/" + fileName)));
                    buffStream.write(bytes);
                    buffStream.close();
                    msg += "You have successfully uploaded " + fileName";
                } catch (Exception e) {
                    return "You failed to upload " + fileName + ": " + e.getMessage();
                }
            }
            return msg;
        } else {
            return "Unable to upload. File is empty.";
        }
    }
}

4.spring-boot 配置上传文件和请求文件的最大值限制:

直接在application.properties中

multipart.maxFileSize=128KB

multipart.maxRequestSize=128KB



5、 spring-boot-starter-webare already added as dependencies. To upload files with Servlet containers, you need to register aMultipartConfigElemen class (which would be multipart-config in
web.xml). Thanks to Spring Boot, everything is auto-configured for you!

spring-boot-upload链接

GitHub 加速计划 / sp / spring-boot
73.97 K
40.4 K
下载
spring-projects/spring-boot: 是一个用于简化Spring应用开发的框架。适合用于需要快速开发企业级Java应用的项目。特点是可以提供自动配置、独立运行和内置的Tomcat服务器,简化Spring应用的构建和部署。
最近提交(Master分支:1 个月前 )
fdf24c6c Closes gh-42976 5 天前
3c42ba8c * pr/42974: Fix copyright year of updated file Polish Closes gh-42974 5 天前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐