1. 程式人生 > >SpringMVC-檔案下載

SpringMVC-檔案下載

    web開發中,檔案的上傳與下載是系統必備的功能。無論是PC端的web系統還是手機APP軟體,發票與合同的下載,對所有的使用者來說都是不可或缺的。
    檔案的下載實質上就是檔案的網路傳輸,其過程是檔案從伺服器經過網路流傳向用戶的本地,其間需要使用者在本地瀏覽器指定下載路徑。
    使用Spring開發時,有三種方式可以實現檔案的下載。分別是:

  1. 超連結
  2. 檔案流
  3. ResponseEntity

1. 超連結

第一種方式比較簡單,使用a標籤:

  1
<a href="url">點選下載</a>
 

就可以實現對靜態資源的下載,但只能下載靜態資源,應用比較侷限。

2. I/O流

使用I/O流下載檔案實質上就是將檔案內容暫存於reponse的訊息體中,然後設定相應型別告知瀏覽器下載檔案,最終啟用瀏覽器的下載視窗,由使用者選擇路徑

 1 @Override
 2 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 3     //
伺服器檔案路徑 4 String serverFilePath = "D:\\Hello world.txt"; 5 File serverFile = new File(serverFilePath); 6 7 // 設定ContentType, 固定寫法 8 response.setContentType("text/html;charset=utf-8"); 9 // 告知瀏覽器下載附件 10 response.addHeader("Content-Disposition", "attachment;filename=" + serverFile.getName());
11 12 // 讀取檔案內容 13 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); 14 InputStream inputStream = null; // 伺服器檔案讀取流 15 try { 16 inputStream = new FileInputStream(serverFile); 17 byte[] buffer = new byte[1024]; 18 int len = 0; 19 while ((len = inputStream.read(buffer)) != -1) { 20 byteArrayOutputStream.write(buffer, 0, len); 21 } 22 } catch (Exception e) { 23 e.printStackTrace(); 24 } 25 byte[] data = byteArrayOutputStream.toByteArray(); 26 27 // 輸出檔案內容到response 28 OutputStream outputStream = response.getOutputStream(); 29 outputStream.write(data); 30 31 // 關閉流 32 FileUtil.closeStream(byteArrayOutputStream, inputStream, outputStream); 33 }

 

3. ResponseEntity

使用I/O流下載檔案的寫法複雜且可讀性非常差。Spring提供了一種比較優雅的方式-ResponseEntity,實現檔案下載。
ResponseEntity類是HttpEntity類的擴充套件類,它只比HttpEntity多了一個狀態屬性。HttpEntity是http請求/響應訊息的抽象實體,包括header和body。
ResponseEntity接收一個內容泛型,在檔案下載時可以指定byte[]型別接收下載檔案內容。

 1 @RequestMapping("/downloadFile")
 2 public ResponseEntity<byte[]> testResponseEntity(HttpServletRequest request, HttpServletResponse response) {
 3     ResponseEntity<byte[]> responseEntity = null;
 4     try {
 5         // 伺服器檔案路徑
 6         String serverFilePath = "D:\\Hello world.txt";
 7         File serverFile = new File(serverFilePath);
 8 
 9         // 響應頭,告知瀏覽器下載附件
10         HttpHeaders headers = new HttpHeaders();
11         headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + serverFile.getName());
12         // 響應內容。
13         byte[] body = FileUtil.readByteArrayFromLocalFile(serverFilePath);
14         // 響應狀態
15         HttpStatus statusCode = HttpStatus.OK;
16 
17         responseEntity = new ResponseEntity(body, headers, statusCode);
18     } catch (Exception e) {
19         e.printStackTrace();
20     }
21     return responseEntity;
22 }