从服务器下载文件的 方法 有 多种
,可以使用
ResponseEntity<InputStreamResource>,。
HttpServletResponse以下是两种下载方法。
@GetMapping("/download1") public ResponseEntity<InputStreamResource> downloadFile1() throws IOException { File file = new File(FILE_PATH); InputStreamResource resource = new InputStreamResource(new FileInputStream(file)); return ResponseEntity.ok() .header(HttpHeaders.CONTENT_DISPOSITION,"attachment;filename=" + file.getName()) .contentType(MediaType.APPLICATION_PDF).contentLength(file.length()) .body(resource); }要么
您可以
StreamingResponseBody用来下载 大
文件。在这种情况下,服务器同时将数据写入
OutputStream浏览器读取的数据,这意味着它是并行的。
@RequestMapping(value = "downloadFile", method = RequestMethod.GET) public StreamingResponseBody getSteamingFile(HttpServletResponse response) throws IOException { response.setContentType("application/pdf"); response.setHeader("Content-Disposition", "attachment; filename="demo.pdf""); InputStream inputStream = new FileInputStream(new File("C:\demo-file.pdf")); return outputStream -> { int nRead; byte[] data = new byte[1024]; while ((nRead = inputStream.read(data, 0, data.length)) != -1) { System.out.println("Writing some bytes.."); outputStream.write(data, 0, nRead); } }; }


