在 Spring Boot 中,可以使用以下两种方式返回 ResponseStream 内容:

  1. 使用 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);
}
  1. 使用 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>
SpringBoot 如何返回 ResponseStream 内容

原文地址: https://www.cveoy.top/t/topic/mzwA 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录