Kumail
Kumail

Reputation: 21

Download process is not visible while servlet is downloading pdf

I m using content-disposition to download pdf . When I click the download button, the complete pdf file is downloaded first and then browser shows the dialog box to save the file. I want the browser to show the process of downloading. The following is my servlet code:

        String filename = "abc.pdf";
        String filepath = "/pdf/" + filename;
        resp.setContentType("application/pdf");
        resp.addHeader("content-disposition", "attachment; filename=" + filename);

        ServletContext ctx = getServletContext();
        InputStream is = ctx.getResourceAsStream(filepath);

        System.out.println(is.toString());
        int read = 0;

        byte[] bytes = new byte[1024];

        OutputStream os = resp.getOutputStream();           
        while ((read = is.read(bytes)) != -1) {
            os.write(bytes, 0, read);
        }
        System.out.println(read);

        os.flush();
        os.close();
        }catch(Exception ex){
            logger.error("Exception occurred while downloading pdf -- "+ex.getMessage());
            System.out.println(ex.getStackTrace());
        }

Upvotes: 2

Views: 868

Answers (1)

BalusC
BalusC

Reputation: 1108722

The progress cannot be determined without knowing the response body's content length beforehand in the client side. To let the client know about the content length, you need to set the Content-Length header in the server side.

Change the line

InputStream is = ctx.getResourceAsStream(filepath);

to

URL resource = ctx.getResource(filepath);
URLConnection connection = resource.openConnection();
response.setContentLength(connection.getContentLength()); // <--- 
InputStream is = connection.getInputStream();
// ...

Unrelated to the concrete problem, your exception handling is bad. Replace the line

System.out.println(ex.getStackTrace());

by

throw new ServletException(ex);

Upvotes: 3

Related Questions