开发者

Download process is not visible while servlet is downloading pdf

开发者 https://www.devze.com 2023-04-04 18:22 出处:网络
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 t

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.setContentTy开发者_开发知识库pe("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());
        }


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号