本來是想做下載畦娄,結(jié)果無意中發(fā)現(xiàn)response不設置頭部即可實現(xiàn)預覽节吮,此代碼也可直接實現(xiàn) 照片弛房,word文檔等預覽开睡。
前端代碼:
注意: target="_black 可以讓pdf在新的網(wǎng)頁打開害驹。
<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");