小文件:直接將文件一次性讀取到內存中,文件大可能會導致OOM
@GetMapping("/download1")public void download1(HttpServletResponse response) throws IOException {// 指定要下載的文件File file = new File("C:\\Users\\syd\\Desktop\\do\\down.txt");// 文件轉成字節數組byte[] fileBytes = Files.readAllBytes(file.toPath());//文件名編碼,防止中文亂碼String filename = URLEncoder.encode(file.getName(), "UTF-8");// 設置響應頭信息response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");// 內容類型為通用類型,表示二進制數據流response.setContentType("application/octet-stream");//輸出文件內容try (OutputStream os = response.getOutputStream()) {os.write(fileBytes);}}
通用大小文件:邊讀邊輸出
@GetMapping("/download")public void download3(HttpServletResponse response) throws IOException {// 指定要下載的文件File file = new File("C:\\Users\\syd\\Desktop\\do\\down.txt");//文件名編碼,防止中文亂碼String filename = URLEncoder.encode(file.getName(), "UTF-8");// 設置響應頭信息response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");// 內容類型為通用類型,表示二進制數據流response.setContentType("application/octet-stream");// 循環,邊讀取邊輸出,可避免大文件時OOMtry (InputStream inputStream = new FileInputStream(file); OutputStream os = response.getOutputStream()) {byte[] bytes = new byte[1024];int readLength;while ((readLength = inputStream.read(bytes)) != -1) {os.write(bytes, 0, readLength);}}}
也可以使用ResponseEntity<Resource>
@GetMapping("/download")public ResponseEntity<Resource> download4() throws IOException {yteArrayResource:字節數組資源*/File file = new File("C:\\Users\\syd\\Desktop\\do\\down.txt");Resource resource = new FileSystemResource(file);//文件名編碼,防止中文亂碼String filename = URLEncoder.encode(file.getName(), "UTF-8");//構建響應實體:ResponseEntity,ResponseEntity中包含了http請求的響應信息,比如狀態碼、頭、bodyResponseEntity<Resource> responseEntity = ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"").header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE).body(resource);return responseEntity;}