美文网首页Java 杂谈
javaWeb项目实现pdf预览

javaWeb项目实现pdf预览

作者: 白桦树97 | 来源:发表于2019-05-13 15:01 被阅读0次

本来是想做下载,结果无意中发现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");

相关文章

网友评论

    本文标题:javaWeb项目实现pdf预览

    本文链接:https://www.haomeiwen.com/subject/lfolaqtx.html