spring-boot上傳文件MultiPartFile獲取不到文件問題解決


1.現象是在spring-boot里加入commons-fileupload jar並且配置了mutilPart的bean,在upload的POST請求后,發現

multipartRequest.getFiles("file")=null,有點奇怪,查了文檔資料才解決。
[java]  view plain  copy
 
  1. <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
  2.        <property name="maxUploadSize" value="104857600"/>  
  3.        <property name="maxInMemorySize" value="4096"/>  
  4.    </bean>  

2.原因是:spring-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]  view plain  copy
 
  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 aMultipartConfigElement class (which would be <multipart-config> in web.xml). Thanks to Spring Boot, everything is auto-configured for you! spring-boot-upload鏈接


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM