blob文件流前端顯示pdf三種方法
更新時間:2024年04月02日 08:42:54 作者:兔老大的胡蘿卜
這篇文章主要給大家介紹了關(guān)于blob文件流前端顯示pdf的三種方法,困擾我一個晚上的問題,終于解決了,文中給出了詳細的代碼示例,需要的朋友可以參考下
首先請求需要修改
responseType: ‘blob’, 需要修改
請求頭 { responseType: 'blob', url: url, method: 'get', }
三種方法:
1.直接處理,在新頁面打開
const blob = new Blob([data],{ type:'application/pdf' }) let url = window.URL.createObjectURL(blob) window.open(url,'_blank') 問題在于父頁面關(guān)閉或者刷新后,文件頁面獲取不到文件流,刷新顯示空白頁。
2.在新頁面用iframe接
<iframe :src='xxxxxx'> 問題在于點擊iframe中文件之后無法在iframe監(jiān)聽事件,ctrl+p 顯示空白
3.使用pdf.js
到 mozilla.github.io/pdf.js/gett… 頁面中找到下載位置,下載 PDF.js 在viewer.js 修改 注釋下列代碼 不然 可能會出現(xiàn)跨域錯誤,無法正常預覽文件 if (origin !== viewerOrigin && protocol !== "blob:") { throw new Error("file origin does not match viewer's"); } 隨后在頁面展示 let path = window.URL.createObjectURL(blob) const fileUrl = '/pdfjs2/web/viewer.html' // 生產(chǎn)環(huán)境下 if (process.env.NODE_ENV === 'production') { this.pdfurl = fileUrl + '?file=' + encodeURIComponent(path) } else { // 開發(fā)環(huán)境 this.pdfurl = fileUrl + '?file=' + encodeURIComponent(path) } 修改清晰度 --注意清晰度越高,打印預覽時 谷歌內(nèi)核滾動條越卡 this._printResolution = 450//printResolution || 150 新版本的pdf.js viewer.js被改為mjs,上線時nginx需要修改 另外還有個bug 在一個頁面打印預覽時,同源的其他頁面無法點擊
附:Blob流在線預覽PDF文件、圖片
這個要注意格式,要加上responseType: 'arraybuffer'
import axios from 'axios' const fileTypeList = ['application/pdf', 'image/png', 'image/gif', 'image/jpeg', 'txt/plain'] invoicePreview () { axios({ method: 'get', url: '/acc_test/index/test_pdf', baseURL: process.env.HOSTURL, responseType: 'arraybuffer' }).then(res => { let fileType = res.headers['content-type'] const binaryData = [] if (fileType && fileTypeList.includes(fileType)) { binaryData.push(res.data) let URL = window.URL.createObjectURL(new Blob(binaryData, { type: fileType, charset: 'utf-8' })) window.open(URL) } else { this.$Message.error('不支持此文件預覽') } }) }
總結(jié)
到此這篇關(guān)于blob文件流前端顯示pdf三種方法的文章就介紹到這了,更多相關(guān)blob文件流顯示pdf內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
javascript 動態(tài)數(shù)據(jù)下的錨點錯位問題解決方法
用 Javascript 實現(xiàn)錨點(Anchor)間平滑跳轉(zhuǎn)2008-12-12