1. 程式人生 > >Spring MVC - MultipartFile實現檔案上傳(單檔案與多檔案上傳)

Spring MVC - MultipartFile實現檔案上傳(單檔案與多檔案上傳)

前提:引入jar包。


   
  1. <dependency>
  2. <groupId>commons-fileupload </groupId>
  3. <artifactId>commons-fileupload </artifactId
    >
  4. <version>1.3 </version>
  5. </dependency>


一、配置檔案:

SpringMVC 用的是 的MultipartFile來進行檔案上傳 所以我們首先要配置MultipartResolver:用於處理表單中的file


   
  1. <!-- SpringMVC上傳檔案時,需要配置MultipartResolver處理器 -->
  2. <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  3. <property
    name="defaultEncoding" value="UTF-8" />
  4. <!-- 指定所上傳檔案的總大小不能超過200KB。注意maxUploadSize屬性的限制不是針對單個檔案,而是所有檔案的容量之和 -->
  5. <!-- <property name="maxUploadSize" value="200000"/> -->
  6. <!-- 指定上傳檔案的臨時路徑 -->
  7. <!-- <property name="uploadTempDir" value="uploadTempDirectory" /> -->
  8. </bean>
屬性詳解:
defaultEncoding="UTF-8"  是請求的編碼格式,預設為iso-8859-1
maxUploadSize="200000"  是上傳檔案的大小,單位為位元組
uploadTempDir="uploadTempDirectory "   為上傳檔案的臨時路徑


二、建立一個簡單的上傳表單:


   
  1. <form action="uploadId" method="post" enctype="multipart/form-data">
  2. <input type="file" name="idPic" />
  3. <button >Submit </button>
  4. </form>
注意:要在form標籤中加上 enctype="multipart/form-data" 表示該表單是要處理檔案的,這是最基本的東西,很多人會忘記然而當上傳出錯後則去找程式的錯誤,卻忘了這一點

三、編寫上傳控制類

1、建立一個控制類: FileUploadController,一個返回提交檔案的頁面
2、編寫提交表單的action:

3、使用SpringMVC註解RequestParam來指定表單中的idPic引數;
4、指定一個用於儲存檔案的web專案路徑
5、通過MultipartFile的transferTo(File dest)這個方法來轉存檔案到指定的路徑。
MultipartFile轉存後,無法再操作,會報錯


   
  1. <span style= "white-space:pre"> </span> //通過Spring的autowired註解獲取spring預設配置的request
  2. @Autowired
  3. private HttpServletRequest request;
  4. <span style= "white-space:pre"> </span> /**
  5. * 跳轉到上傳檔案的頁面
  6. * @return
  7. */
  8. @RequestMapping(value = "/uploadPage")
  9. public String uploadPage() {
  10. return "upload";
  11. }
  12. /**
  13. * 上傳檔案 用@RequestParam註解來指定表單上的file為MultipartFile
  14. * @param multipartfile
  15. * @return
  16. * @throws IOException
  17. */
  18. @RequestMapping(value = "/uploadId")
  19. @ResponseBody
  20. public ResponseEntity< byte[]> idIdentification( @RequestParam( "idPic") MultipartFile multipartfile) throws IOException {
  21. System.out.println( "getOriginalFilename:"+multipartfile.getOriginalFilename());
  22. System.out.println( "getName:"+multipartfile.getName());
  23. // 設定格式,圖片
  24. HttpHeaders headers = new HttpHeaders();
  25. headers.setContentType(MediaType.IMAGE_JPEG);
  26. //儲存檔案到臨時目錄
  27. String savePath = request.getSession().getServletContext().getRealPath( "/")
  28. + "/uploadTempDirectory/" + multipartfile.getOriginalFilename();
  29. File saveFile = new File(savePath);
  30. multipartfile.transferTo(saveFile);
  31. //頁面顯示使用者上傳的圖片
  32. return new ResponseEntity< byte[]>(FileUtils.readFileToByteArray(saveFile), headers, HttpStatus.OK);
  33. }


到此基本的檔案上傳就結束了。


多檔案上傳:

多檔案上傳其實很簡單,和上傳其他相同的引數如checkbox一樣,表單中使用相同的名稱,然後action中將MultipartFile引數類定義為陣列就可以。
接下來實現:

1、建立一個上傳多檔案的表單:


   
  1. <form action="multiUploadId" method="post" enctype="multipart/form-data">
  2. <input type="file" name="idPic" />
  3. <input type="file" name="idPic" />
  4. <input type="file" name="idPic" />
  5. <button >Submit </button>
  6. </form>

2、編寫處理表單的action:


   
  1. <span style= "white-space:pre"> </span> /**
  2. * 多檔案上傳
  3. * @param multipartfiles
  4. * @return
  5. * @throws IllegalStateException
  6. * @throws IOException
  7. */
  8. @RequestMapping(value = "/multiUploadId")
  9. public String multiUpload(@RequestParam("idPic") MultipartFile[] multipartfiles)
  10. throws IllegalStateException, IOException {
  11. //儲存檔案的目錄
  12. String savePath = request.getSession().getServletContext().getRealPath( "/") + "/uploadTempDirectory/";
  13. if( null != multipartfiles && multipartfiles.length > 0){
  14. //遍歷並儲存檔案
  15. for(MultipartFile file : multipartfiles){
  16. file.transferTo( new File(savePath + file.getOriginalFilename()));
  17. }
  18. }
  19. return "redirect:uploadPage";
  20. }

執行例項,大功告成!