springboot怎么返回responseSteam
在 Spring Boot 中,可以使用以下方式返回 ResponseSteam:
- 使用 ResponseEntity:
@GetMapping("/download")
public ResponseEntity<Resource> downloadFile() throws IOException {
InputStreamResource resource = new InputStreamResource(new FileInputStream("path/to/file"));
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=file.txt")
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.contentLength(resource.contentLength())
.body(resource);
}
- 使用 HttpServletResponse:
@GetMapping("/download")
public void downloadFile(HttpServletResponse response) throws IOException {
response.setContentType("application/octet-stream");
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=file.txt");
InputStream inputStream = new FileInputStream("path/to/file");
IOUtils.copy(inputStream, response.getOutputStream());
response.flushBuffer();
}
其中,IOUtils 是 Apache Commons IO 库中的工具类,用于将 InputStream 内容拷贝到 OutputStream。需要在 pom.xml 中添加以下依赖:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.8.0</version>
</dependency>
原文地址: https://www.cveoy.top/t/topic/9CE 著作权归作者所有。请勿转载和采集!