0

In my Servlet I would need to propose a file download to the end user and also display an HTML page indicating the status of the download.

I read that it was not possible to use both OutputStream and PrintWriter on the same response, but by reading this post, I tried to make it working...but no success...

I tried the following:

        try(InputStream in = new FileInputStream(new File(bf.path));
        ServletOutputStream out = response.getOutputStream()) { 

        byte[] buffer = new byte[1048];        
        int numBytesRead;
        while ((numBytesRead = in.read(buffer)) > 0) {
            out.write(buffer, 0, numBytesRead);
        }

        out.flush();

        PrintWriter print = new PrintWriter(new OutputStreamWriter(out, "utf-8"));

        print.println("<html>");
        print.println("</html>");
        print.flush();
        print.close();
        }

The download is proceeded successfully but my HTML content is never displayed...I also tried to perform the PrintWriter before the file download but same result...no HTML content displayed.

I also tried with PrintStream print = new PrintStream(out, true, "utf-8");

but same thing... any idea on how I can propose a file download and display HTML content on the same Servlet ?

tiamat
  • 879
  • 2
  • 12
  • 35
  • yes I tried to remove the flush as well...same thing... – tiamat Oct 06 '22 at 10:02
  • 1
    I also tried the redirect approach but it gives me the following error: "java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed" – tiamat Oct 06 '22 at 10:08
  • (create) Multipart response: https://stackoverflow.com/q/45066064/592355 – xerx593 Oct 06 '22 at 10:09
  • Not able to find a way to manage a MultiPart Response containing both HTML content to be displayed and a File Download...it seems to be applied for Mail... – tiamat Oct 06 '22 at 14:52
  • This makes no sense. You're basically trying to append HTML code to the downloaded file. Have you actually looked closer at the contents of the downloaded file? See the currently accepted answer of the abovelinked duplicate for the solution. – BalusC Oct 06 '22 at 15:49

0 Answers0