spring-boot上传文件MultiPartFile获取不到文件问题解决
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
spring-boot上传⽂件MultiPartFile获取不到⽂件问题解决
1.现象是在spring-boot⾥加⼊commons-fileupload jar并且配置了mutilPart的bean,在upload的POST请求后,发现
multipartRequest.getFiles("file")=null,有点奇怪,查了⽂档资料才解决。
[java]
1. <bean id="multipartResolver" class="monsMultipartResolver">
2. <property name="maxUploadSize" value="104857600"/>
3. <property name="maxInMemorySize" value="4096"/>
4. </bean>
2.原因是:-boot⾃带的org.springframework.web.multipart.MultipartFile
和Multipart产⽣冲突,如果同时使⽤了MultipartResolver 和ServletFileUpload,就会在iter.hasNext()返回false.然后整个循环就跳出去了。
整个问题产⽣的原因是Spring框架先调⽤了MultipartResolver 来处理http multi-part的请求。
这⾥http multipart的请求已经消耗掉。
后⾯⼜交给ServletFileUpload ,那么ServletFileUpload 就获取不到相应的multi-part请求。
因此将multipartResolve配置去除,问题就解决了。
3. 单⽂件的话只需要⼀个变量即,多⽂件上传的话就将MultipartFile改为数组,然后分别上传保存即可。
[java]
1. @RequestMapping(value="/multipleSave", method=RequestMethod.POST )
2. public @ResponseBody String multipleSave(@RequestParam("file") MultipartFile[] files){
3. String fileName = null;
4. String msg = "";
5. if (files != null && files.length >0) {
6. for(int i =0 ;i< files.length; i++){
7. try {
8. fileName = files[i].getOriginalFilename();
9. byte[] bytes = files[i].getBytes();
10. BufferedOutputStream buffStream =
11. new BufferedOutputStream(new FileOutputStream(new File("/tmp/" + fileName)));
12. buffStream.write(bytes);
13. buffStream.close();
14. msg += "You have successfully uploaded " + fileName";
15. } catch (Exception e) {
16. return "You failed to upload " + fileName + ": " + e.getMessage();
17. }
18. }
19. return msg;
20. } else {
21. return "Unable to upload. File is empty.";
22. }
23. }
24. }
4.spring-boot 配置上传⽂件和请求⽂件的最⼤值限制:
直接在application.properties中
multipart.maxFileSize=128KB
multipart.maxRequestSize=128KB
5. spring-boot-starter-web are already added as dependencies. To upload files with Servlet containers, you need to register
a MultipartConfigElement class (which would be <multipart-config> in web.xml). Thanks to Spring Boot, everything is auto-configured for you!。