当servlet下载pdf时,下载过程不可见

时间:2011-09-13 13:44:50

标签: java servlets download

我使用内容处理来下载pdf。单击下载按钮时,首先下载完整的pdf文件,然后浏览器显示保存文件的对话框。我希望浏览器显示下载过程。以下是我的servlet代码:

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

1 个答案:

答案 0 :(得分:3)

如果事先未在客户端知道响应主体的内容长度,则无法确定进度。要让客户端了解内容长度,您需要在服务器端设置Content-Length标头。

更改行

InputStream is = ctx.getResourceAsStream(filepath);

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

对具体问题

无关,您的异常处理很糟糕。替换

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

通过

throw new ServletException(ex);