1、控制器程式碼
@PostMapping('/clientDownload') public void clientDownload(HttpServletResponse response){ try { return FileUtils.downloadFile(filePath,downloadnFileName,response); } catch (Exception e) { throw new RuntimeException(e); } } @PostMapping('/download') public ResponseEntity<InputStreamResource> download(@RequestParam Integer id){ try { return FileUtils.fileDownload(new File(file.getFilePath()),file.getFileName()); } catch (Exception e) { throw new RuntimeException(e); } }
2、檔案下載工具類FileUtils.java
/** * @description: 直接下載檔案 * @date: 2024/11/30 16:28 * @param file * @param downloadFileName * @return org.springframework.http.ResponseEntity<org.springframework.core.io.InputStreamResource> */ public static ResponseEntity<InputStreamResource> fileDownload(File file, String downloadFileName) { InputStream is; InputStreamResource resource; try { String fileName = StringUtils.isNotBlank(downloadFileName) ? downloadFileName : file.getName(); fileName = URLEncoder.encode(fileName,'UTF-8'); is = new FileInputStream(file); resource = new InputStreamResource(is); HttpHeaders headers = new HttpHeaders(); headers.add('Content-Disposition', 'attachment; filename=\'' + fileName + '\''); headers.add('Cache-Control', 'no-cache, no-store, must-revalidate'); headers.add('Pragma', 'no-cache'); headers.add('Expires', '0'); return ResponseEntity.ok() .headers(headers) .contentLength(is.available()) .contentType(MediaType.parseMediaType('application/octet-stream')) .body(resource); } catch (IOException e) { String errMsg = '檔案下載異常:' + e.toString(); log.info(errMsg); throw new DTOCheckException(errMsg); } } /** * @description: 以流的形式下載檔案 * @date: 2024/11/30 17:29 * @param path * @param downloadFileName * @param response * @return javax.servlet.http.HttpServletResponse */ public static HttpServletResponse downloadFile(String path,String downloadFileName, HttpServletResponse response) { try { File file = new File(path); String fileName = StringUtils.isNotBlank(downloadFileName) ? downloadFileName : file.getName(); fileName = URLEncoder.encode(fileName,'UTF-8'); // 以流的形式下載檔案 InputStream fis = new BufferedInputStream(new FileInputStream(path)); byte[] buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); // 清空response response.reset(); // 設定response的Header response.addHeader('Content-Disposition', 'attachment;filename=' + fileName); response.addHeader('Content-Length', '' + file.length()); OutputStream toClient = new BufferedOutputStream(response.getOutputStream()); response.setContentType('application/octet-stream'); toClient.write(buffer); toClient.flush(); toClient.close(); } catch (IOException ex) { ex.printStackTrace(); } return response; }