jFinal在线预览pdf文件

一:页面

<a href="/upload/downLoad">在线预览</a>

二:代码

public void downLoad() throws Exception {
HttpServletResponse response = getResponse();
boolean boo = true;
String filePath = "E:\\file\\2018\\demo\\1PB.pdf";
File f = new File(filePath);
if (!f.exists()) {
response.sendError(404, "File not found!");
return;
}
BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
byte[] buf = new byte[1024];
int len = 0;
response.reset(); // 非常重要
if (boo) { // 在线打开(预览)
URL u = new URL("file:///" + filePath);
response.setContentType(u.openConnection().getContentType());
response.setHeader("Content-Disposition", "inline; filename=" + f.getName());
} else { //下载
response.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition", "attachment; filename=" + f.getName());
}
OutputStream out = response.getOutputStream();
while ((len = br.read(buf)) > 0)
out.write(buf, 0, len);
br.close();
out.close();

}

三:参考文档

http://blog.csdn.net/pangqiandou/article/details/53234586

猜你喜欢

转载自blog.csdn.net/m0_37934074/article/details/79291962