本来是想做下载,结果无意中发现response不设置头部即可实现预览,此代码也可直接实现 照片,word文档等预览。
前端代码:
注意: target="_black 可以让pdf在新的网页打开。
<a href="<%=path%>/DownLoadPdf?fileName=${rec}" target="_black">预览</a>
后端代码:
@WebServlet(name = "DownLoadPdf")
public class DownLoadPdf extends HttpServlet {
protected void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
String fileName = request.getParameter("fileName");
if(fileName!=null){
String realPath = request.getSession().getServletContext().getRealPath("/attachFiles/detections/");
File file = new File(realPath+fileName);
FileInputStream fis = new FileInputStream(file);
ServletOutputStream out = response.getOutputStream();
byte[] buf = new byte[4096];
int len = -1;
while ((len = fis.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.flush();
fis.close();
out.close();
}
}
}
若要进行下载,则加入以下代码。
response.setHeader("Content-Disposition", "attachment; filename=\""
+ fileName + "\"");
response.addHeader("Content-Length", file.length() + "");
response.setContentType("application/octet-stream");