项目中需要通过链接来预览pdf,代码如下:
<a href=" w e b p a t h / d o w n / p r e v i e w U r l . p a g e ? i d = web_path/down/previewUrl.page?id= webpath/down/previewUrl.page?id=!orderDetail.insurePolicyNo" target=“view_window”"
style=“width:85px;height:40px;line-height: 40px;font-size:12px;color:#fff;background: #1c9af1;text-align: center;padding: 2px;border-radius: 3px;”>预览pdf
private void preview(String path, HttpServletRequest request, HttpServletResponse response) {
File file = new File(path);
if (!file.exists()) {
request.setAttribute("error", "附件已删除或不存在");
}
InputStream in = null;
OutputStream os = null;
try {
response.setContentType("application/pdf"); // 设置返回内容格式
in = new FileInputStream(file); //用该文件创建一个输入流
os = response.getOutputStream(); //创建输出流
byte[] b = new byte[1024];
while (in.read(b) != -1) {
os.write(b);
}
in.close();
os.flush();
os.close();
} catch (Exception e) {
try {
if (null != in) {
in.close();
}
if (null != os) {
os.close();
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
}