欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

blob文件流前端顯示pdf三種方法

 更新時(shí)間:2024年04月02日 08:42:54   作者:兔老大的胡蘿卜  
這篇文章主要給大家介紹了關(guān)于blob文件流前端顯示pdf的三種方法,困擾我一個(gè)晚上的問題,終于解決了,文中給出了詳細(xì)的代碼示例,需要的朋友可以參考下

首先請(qǐng)求需要修改

responseType: ‘blob’, 需要修改

請(qǐng)求頭
{
        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'>
問題在于點(diǎn)擊iframe中文件之后無法在iframe監(jiān)聽事件,ctrl+p 顯示空白

3.使用pdf.js

到 mozilla.github.io/pdf.js/gett… 頁面中找到下載位置,下載 PDF.js
在viewer.js 修改
注釋下列代碼   不然 可能會(huì)出現(xiàn)跨域錯(cuò)誤,無法正常預(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ù)覽時(shí) 谷歌內(nèi)核滾動(dòng)條越卡
this._printResolution = 450//printResolution || 150
新版本的pdf.js viewer.js被改為mjs,上線時(shí)nginx需要修改
另外還有個(gè)bug 在一個(gè)頁面打印預(yù)覽時(shí),同源的其他頁面無法點(diǎn)擊

附:Blob流在線預(yù)覽PDF文件、圖片

這個(gè)要注意格式,要加上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)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論