首先请求需要修改
responseType: ‘blob’, 需要修改
1 2 3 4 5 6 | 请求头 { responseType: 'blob' , url: url, method: 'get' , } |
三种方法:
1.直接处理,在新页面打开
1 2 3 4 5 6 | const blob = new Blob([data],{ type: 'application/pdf' }) let url = window.URL.createObjectURL(blob) window.open(url, '_blank' ) 问题在于父页面关闭或者刷新后,文件页面获取不到文件流,刷新显示空白页。 |
2.在新页面用iframe接
1 | 问题在于点击iframe中文件之后无法在iframe监听事件,ctrl+p 显示空白 |
3.使用pdf.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | 到 mozilla.github.io/pdf.js/gett… 页面中找到下载位置,下载 PDF.js 在viewer.js 修改 注释下列代码 不然 可能会出现跨域错误,无法正常预览文件 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 ' // 生产环境下 if (process.env.NODE_ENV === ' production ') { this.pdfurl = fileUrl + ' ?file= ' + encodeURIComponent(path) } else { // 开发环境 this.pdfurl = fileUrl + ' ?file=' + encodeURIComponent(path) } 修改清晰度 --注意清晰度越高,打印预览时 谷歌内核滚动条越卡 this ._printResolution = 450 //printResolution || 150 新版本的pdf.js viewer.js被改为mjs,上线时nginx需要修改 另外还有个bug 在一个页面打印预览时,同源的其他页面无法点击 |
附:Blob流在线预览PDF文件、图片
这个要注意格式,要加上responseType: ‘arraybuffer’
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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( '不支持此文件预览' ) } }) } |
总结
到此这篇关于blob文件流前端显示pdf三种方法的文章就介绍到这了,更多相关blob文件流显示pdf内容请搜索IT俱乐部以前的文章或继续浏览下面的相关文章希望大家以后多多支持IT俱乐部!