使用内容配置下载 pdf servlet 在 IE、chrome 和 firefox 中无法正常工作,但在 Opera 中则不行
我正在使用内容配置从我的 servlet 下载 pdf 文件。我的代码适用于 chrome、firefox 和 IE,但问题是当我尝试使用 Opera 下载 pdf 文件时,它会删除 pdf 扩展名并添加 htm。以下是我的代码:
String filename = "abc.pdf";
String filepath = "/pdf/" + filename;
System.out.println("filepath "+filepath);
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());
}
I m using content disposition to download pdf file from my servlet. My code works fine for chrome, firefox and IE but the problem is when I try to download pdf file using opera, it removes pdf extension and adds htm. The following is my code:
String filename = "abc.pdf";
String filepath = "/pdf/" + filename;
System.out.println("filepath "+filepath);
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());
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可能应该将响应的内容类型设置为
application/pdf
,让浏览器知道下载的文件不是 HTML 文件,而是 PDF 文件。请参阅
ServletResponse.setContentType()
。You should probably set the content type of the response to
application/pdf
, to let the browser know that the downloaded file is not a HTML file, but a PDF file.See
ServletResponse.setContentType()
.