Java后端返回PDF預(yù)覽給前端的實現(xiàn)
前端要預(yù)覽服務(wù)器PDF 可直接將要blob流返回給前端 即可用瀏覽器自帶pdf預(yù)覽功能打開,現(xiàn)有兩種方式
方式1 返回blob流給前端 代碼如下
@PostMapping(value = "/preview") @ResponseBody public void showPdf(HttpServletResponse response) { try { File file = new File("filePath"); OutputStream out = null; try (BufferedInputStream br = new BufferedInputStream(new FileInputStream(file)); ) { byte[] bs = new byte[1024]; int len; response.reset(); // 非常重要 URL u = new URL("file:///" + "filePath"); String contentType = u.openConnection().getContentType(); response.setContentType(contentType); response.setHeader("Content-Disposition", "inline;filename=" + "preview.pdf"); out = response.getOutputStream(); while ((len = br.read(bs)) > 0) { out.write(bs, 0, len); } out.flush(); out.close(); } } catch (Exception e) { e.printStackTrace(); } }
此時 前端解析可直接拿返回的文件流 例子如下
let blob = this.response; const binaryData = []; binaryData.push(blob); const url = window.URL.createObjectURL(new Blob(binaryData, { type: 'application/pdf' })); window.open(url);
但有的時候 不想返回文件流 可把文件返回為base64 (注意 base64可能超長)此時代碼修改如下
File file = new File("filePath"); OutputStream out = null; try (BufferedInputStream br = new BufferedInputStream(new FileInputStream(file)); ByteArrayOutputStream outStream = new ByteArrayOutputStream(); ) { int len; URL u = new URL("file:///" + "filePath"); String contentType = u.openConnection().getContentType(); byte[] buffer = new byte[1024]; //每次讀取的字符串長度,如果為-1,代表全部讀取完畢 //使用輸入流從buffer里把數(shù)據(jù)讀取出來 while ((len = br.read(buffer)) != -1) { //用輸出流往buffer里寫入數(shù)據(jù),中間參數(shù)代表從哪個位置開始讀,len代表讀取的長度 outStream.write(buffer, 0, len); } // 對字節(jié)數(shù)組Base64編碼 Base64Encoder base64 = new Base64Encoder(); String base64Str = replaceEnter(base64.encode(outStream.toByteArray())); } } catch (Exception e) { }
前端修改如下
let base64 = resBase64.data.base64; base64 = base64.replace(/[\n\r]/g, '') const raw = window.atob(base64) const rawLength = raw.length const uInt8Array = new Uint8Array(rawLength) for (let i = 0; i < rawLength; ++i) { uInt8Array[i] = raw.charCodeAt(i) } const url = window.URL.createObjectURL(new Blob([uInt8Array], { type: resBase64.data.contentType })); window.open(url);
到此這篇關(guān)于Java后端返回PDF預(yù)覽給前端的實現(xiàn)的文章就介紹到這了,更多相關(guān)Java 返回PDF預(yù)覽給前端內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java使用easyExcel批量導(dǎo)入數(shù)據(jù)詳解
這篇文章主要介紹了Java使用easyExcel批量導(dǎo)入數(shù)據(jù)詳解,通常我們會提供一個模板,此模塊我們可以使用easyExcel導(dǎo)出數(shù)據(jù)生成的一個Excel文件當(dāng)作模板,提供下載鏈接,用戶在該文件內(nèi)填入規(guī)定的數(shù)據(jù)格式以后可以批量導(dǎo)入數(shù)據(jù)到數(shù)據(jù)庫中,需要的朋友可以參考下2023-08-08SpringBoot+kaptcha實現(xiàn)圖片驗證碼功能詳解
這篇文章主要為大家詳細介紹了SpringBoot如何結(jié)合kaptcha實現(xiàn)圖片驗證碼功能,文中的示例代碼講解詳細,有需要的小伙伴可以參考一下2024-01-01springboot設(shè)置了server.port但是沒有用,還是8080問題
這篇文章主要介紹了springboot設(shè)置了server.port但是沒有用,還是8080問題的解決,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-12-12