springboot整合pdf.js用檔案流預覽本地磁碟pdf檔案
阿新 • • 發佈:2018-11-19
背景
最近專案中有需求需要在前端上傳pdf檔案並進行預覽,上傳功能比較簡單。而pdf預覽的話,在網上對比個多個外掛後,確定使用pdf.js外掛進行pdf的展示。
官網地址:[http://mozilla.github.io/pdf.js/]
程式碼實現
將pdf.js檔案放入專案資原始檔目錄中,(例中使用springboot目錄架構)
前端js程式碼
$(".previewBtn").click(function () { var curWwwPath=window.document.location.href; var pathName=window.document.location.pathname; var pos=curWwwPath.indexOf(pathName); var localhostPath=curWwwPath.substring(0,pos); window.open(localhostPath+"/pdfjs/web/viewer.html?file="+attachmentUrl + "/preview?fileName=%3Dtest.pdf"); });
注意:直接訪問專案中的viewer.html即可使用pdf.js,而路徑後面的”file=引數”為固定格式,可以使用專案相對路徑
file=./09.pdf直接訪問專案目錄中的pdf檔案。也可以加上後端請求的url,從後端讀取磁碟檔案轉化為檔案流,外掛會自動根據檔案流展示(如file=/admin/data/attachment/preview?fileName%3Dtest.pdf) 注<%3D為’=’的轉義符>
springmvc後臺程式碼
/** * 預覽pdf檔案 * @param fileName */ @RequestMapping(value = "/preview", method = RequestMethod.GET) public void pdfStreamHandler(String fileName,HttpServletRequest request,HttpServletResponse response) { File file = new File("D:/temp/test01/0/"+fileName); if (file.exists()){ byte[] data = null; try { FileInputStream input = new FileInputStream(file); data = new byte[input.available()]; input.read(data); response.getOutputStream().write(data); input.close(); } catch (Exception e) { logger.error("pdf檔案處理異常:" + e.getMessage()); } }else{ return; } }
效果圖