1. 程式人生 > >【springboot】spring-boot上傳檔案MultiPartFile獲取不到檔案問題解決

【springboot】spring-boot上傳檔案MultiPartFile獲取不到檔案問題解決

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!