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)跨域錯誤,無法正常預(yù)覽文件 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) } 修改清晰度 --注意清晰度越高,打印預(yù)覽時 谷歌內(nèi)核滾動條越卡 this._printResolution = 450//printResolution || 150 新版本的pdf.js viewer.js被改為mjs,上線時nginx需要修改 另外還有個bug 在一個頁面打印預(yù)覽時,同源的其他頁面無法點擊
附:Blob流在線預(yù)覽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('不支持此文件預(yù)覽') } }) }
總結(jié)
到此這篇關(guān)于blob文件流前端顯示pdf三種方法的文章就介紹到這了,更多相關(guān)blob文件流顯示pdf內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
BootStrap中的Fontawesome 圖標(biāo)
這篇文章主要介紹了BootStrap中Fontawesome 圖標(biāo)的相關(guān)知識,需要的朋友可以參考下2017-05-05Js數(shù)組對象如何根據(jù)多個key值進(jìn)行分類
這篇文章主要介紹了Js數(shù)組對象如何根據(jù)多個key值進(jìn)行分類,每周從 npm 下載?lodash.groupBy?的次數(shù)在 150 萬到 200 萬之間,很高興看到 JavaScript 填補(bǔ)了這些空白,讓我們的工作變得更加輕松,需要的朋友可以參考下2024-02-02javascript 動態(tài)數(shù)據(jù)下的錨點錯位問題解決方法
用 Javascript 實現(xiàn)錨點(Anchor)間平滑跳轉(zhuǎn)2008-12-12