我使用内容处理从我的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());
}
答案 0 :(得分:2)
您应该将响应的内容类型设置为application/pdf
,让浏览器知道下载的文件不是HTML文件,而是PDF文件。