我使用内容处理来下载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());
}
答案 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);