0

I have an InputStream to a file obtained from a server through SSH using JSch. I want to return it as a file in my Spring Boot application.

Try using ResponseEntity as I read on many forums but it doesn't work

MauriRamone
  • 469
  • 1
  • 3
  • 21
  • You can also use this: File file = new File("file.txt"); FileUtils.copyInputStreamToFile(inputStream, file); response.setContentType("application/force-download"); response.setHeader("Content-Disposition", "attachment;filename=" + "file.txt"); return new HttpEntity(new FileSystemResource(file)); – Inanc Cakil Nov 28 '21 at 10:07

2 Answers2

3

You could use the HttpServletResponse like this:

 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);
}
Shai Givati
  • 1,106
  • 1
  • 10
  • 24
  • Thank you very much, I solved it as I show in https://stackoverflow.com/questions/69044862/direct-file-streaming-from-ssh-using-java/69045057#69045057 – MauriRamone Sep 06 '21 at 18:35
  • See also [Easy way to write contents of a Java InputStream to an OutputStream](https://stackoverflow.com/q/43157/850848). – Martin Prikryl Sep 06 '21 at 18:39
  • It seems that a code like above is blocking and the download on the client side will effectively start only after the SFTP download finished. And consequently the web server will have to keep whole file in memory. After all, were this not true, setting headers (`Cache-Control` and `Expires`) only after the download could never work (as headers are sent to the client before the contents). It seems that more efficient solution is `StreamingResponseBody` (as suggested by @shazin). – Martin Prikryl Sep 07 '21 at 05:29
1

You can use StreamingResponseBody read this post written by me to see an example on how to how to send a file stream.

shazin
  • 21,379
  • 3
  • 54
  • 71
  • Thank you very much, I solved it as I show in https://stackoverflow.com/questions/69044862/direct-file-streaming-from-ssh-using-java/69045057#69045057 – MauriRamone Sep 06 '21 at 18:34
  • You seem to be right, but can you expand your answer a bit (showing how your you use `InputStream` or `OutputStream` from 3rd party API together with `StreamingResponseBody`). See the question linked by OP for some context. – Martin Prikryl Sep 07 '21 at 05:31