Spring boot下載檔案的2種方式
阿新 • • 發佈:2021-01-21
Spring boot中下載檔案的2種方式
1. 通過HttpServletResponse的OutputStream實現
@RequestMapping("/download") public String downloadFile(HttpServletRequest request, HttpServletResponse response) { log.info("進入下載方法。。。。"); String fileName = "CentOS-7-x86_64-Minimal-1810.iso";// 設定檔名,根據業務需要替換成要下載的檔名 if (fileName != null) { //設定檔案路徑 String realPath = "D:\\tmp\\"; File file = new File(realPath , fileName); if (file.exists()) { response.setContentType("application/octet-stream");// response.setHeader("content-type", "application/octet-stream"); response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);// 設定檔名 byte[] buffer = new byte[1024]; FileInputStream fis = null; BufferedInputStream bis = null; try { fis = new FileInputStream(file); bis = new BufferedInputStream(fis); OutputStream os = response.getOutputStream(); int i = bis.read(buffer); while (i != -1) { os.write(buffer, 0, i); i = bis.read(buffer); } System.out.println("success"); } catch (Exception e) { e.printStackTrace(); } finally { if (bis != null) { try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } if (fis != null) { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } } } return null; }
2. 通過ResponseEntity<InputStreamResource>實現
@RequestMapping(value = "/download", method = RequestMethod.GET) public ResponseEntity<InputStreamResource> downloadFile(String fileName) throws IOException { log.info("進入下載方法..."); //讀取檔案 String filePath = "D:/tmp/" + fileName + ".iso"; FileSystemResource file = new FileSystemResource(filePath); //設定響應頭 HttpHeaders headers = new HttpHeaders(); headers.add("Cache-Control", "no-cache, no-store, must-revalidate"); headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getFilename())); headers.add("Pragma", "no-cache"); headers.add("Expires", "0"); return ResponseEntity .ok() .headers(headers) .contentLength(file.contentLength()) .contentType(MediaType.parseMediaType("application/octet-stream")) .body(new InputStreamResource(file.getInputStream())); }