Search code examples
javaspring-bootsshinputstreamjsch

How to return an InputStream as a file in Spring Boot?


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


Solution

  • 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);
    }