2011-09-13 35 views
2

我使用内容配置下载pdf。当我点击下载按钮时,首先下载完整的pdf文件,然后浏览器显示对话框以保存文件。我希望浏览器显示下载过程。以下是我的servlet代码:下载过程在servlet下载时不可见pdf

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

回答

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(); 
// ... 

无关到具体的问题,你的异常处理是坏的。通过

throw new ServletException(ex); 
替换行

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