【问题标题】:How to return an InputStream as a file in Spring Boot? [duplicate]如何在 Spring Boot 中将 InputStream 作为文件返回? [复制]
【发布时间】:2021-11-01 22:08:36
【问题描述】:

我有一个使用 JSch 通过 SSH 从服务器获取的文件的 InputStream。我想在我的 Spring Boot 应用程序中将它作为文件返回。

尝试使用我在许多论坛上阅读的 ResponseEntity,但它不起作用

【问题讨论】:

  • 你也可以这样使用:File file = new File("file.txt"); FileUtils.copyInputStreamToFile(inputStream, file); response.setContentType("应用程序/强制下载"); response.setHeader("Content-Disposition", "attachment;filename=" + "file.txt"); return new HttpEntity(new FileSystemResource(file));

标签: java spring-boot ssh inputstream jsch


【解决方案1】:

您可以使用StreamingResponseBody 阅读我编写的post 以查看有关如何发送文件流的示例。

【讨论】:

  • 非常感谢,我已经解决了,正如我在stackoverflow.com/questions/69044862/…中显示的那样
  • 您似乎是对的,但您能否扩展您的答案(展示您如何使用来自 3rd 方 API 的 InputStreamOutputStream 以及 StreamingResponseBody)。有关某些上下文,请参阅 OP 链接的问题。
【解决方案2】:

您可以像这样使用 HttpServletResponse:

 public static void sendFileInResponse (HttpServletResponse response, InputStream inputStream) throws IOException {
    response.setContentType("your_content_type");
    response.setHeader("Content-Disposition", "inline;filename=your_file_name");
    OutputStream outputStream = response.getOutputStream();
    byte[] buff = new byte[2048];
    int length = 0;
    while ((length = inputStream.read(buff)) > 0) {
        outputStream.write(buff, 0, length);
        outputStream.flush();
    }
    outputStream.close();
    inputStream.close();
    response.setHeader("Cache-Control", "private");
    response.setDateHeader("Expires", 0);
}

【讨论】:

  • 非常感谢,我已经解决了,正如我在stackoverflow.com/questions/69044862/…中显示的那样
  • 似乎上面的代码被阻塞了,客户端的下载只有在 SFTP 下载完成后才会有效地开始。因此,Web 服务器必须将整个文件保存在内存中。毕竟,如果这不是真的,仅在下载之后设置标头(Cache-ControlExpires)永远不会起作用(因为标头在内容之前发送到客户端)。似乎更有效的解决方案是StreamingResponseBody(正如@shazin 所建议的那样)。
猜你喜欢
  • 2020-05-05
  • 2019-05-20
  • 1970-01-01
  • 1970-01-01
  • 2021-11-26
  • 2022-12-07
  • 2021-10-28
  • 2013-07-29
  • 2013-01-07
相关资源
最近更新 更多