小文件:直接将文件一次性读取到内存中,文件大可能会导致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;}