1、返回文件作为响应体,使用ResponseEntity
类:
@GetMapping("/downloadFile") public ResponseEntity<byte[]> downloadFile() throws IOException { // 读取文件内容到字节数组 byte[] fileContent = Files.readAllBytes(Paths.get("path/to/file.txt")); // 设置响应头,指定文件名 HttpHeaders headers = new HttpHeaders(); headers.setContentDisposition(ContentDisposition.attachment().filename("file.txt").build()); // 返回文件内容和响应头 return ResponseEntity.ok().headers(headers).body(fileContent); }
2、返回文件作为响应体,使用StreamingResponseBody
接口:
@GetMapping("/downloadFile") public void downloadFile(HttpServletResponse response) throws IOException { // 设置响应头,指定文件名 response.setHeader("Content-Disposition", "attachment; filename=file.txt"); // 获取文件输入流 InputStream inputStream = new FileInputStream("path/to/file.txt"); // 创建StreamingResponseBody对象,将文件内容写入响应输出流 StreamingResponseBody responseBody = outputStream -> { byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } inputStream.close(); }; // 返回StreamingResponseBody对象 response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE); responseBody.writeTo(response.getOutputStream()); }
3、返回文件下载,使用ResponseEntity
类:
@GetMapping("/downloadFile") public ResponseEntity<Resource> downloadFile() { // 创建Resource对象,表示文件路径 Resource fileResource = new FileSystemResource("path/to/file.txt"); // 设置响应头,指定文件名 HttpHeaders headers = new HttpHeaders(); headers.setContentDisposition(ContentDisposition.attachment().filename("file.txt").build()); // 返回文件资源和响应头 return ResponseEntity.ok().headers(headers).body(fileResource); }
4、返回文件流,使用InputStreamResource
类:
@GetMapping("/downloadFile") public ResponseEntity<InputStreamResource> downloadFile() throws FileNotFoundException { // 创建文件输入流 FileInputStream fileInputStream = new FileInputStream("path/to/file.txt"); // 创建InputStreamResource对象,封装文件输入流 InputStreamResource resource = new InputStreamResource(fileInputStream); // 设置响应头,指定文件名 HttpHeaders headers = new HttpHeaders(); headers.setContentDisposition(ContentDisposition.attachment().filename("file.txt").build()); // 返回InputStreamResource对象和响应头 return ResponseEntity.ok().headers(headers).body(resource); }
标签:file,spring,boot,downloadFile,headers,ResponseEntity,new,txt,下载 From: https://www.cnblogs.com/shining-feifan/p/17387982.html