首先请求需要修改
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') 问题在于父页面关闭或者刷新后,文件页面获取不到文件流,刷新显示空白页。
2.在新页面用iframe接
<iframe :src='xxxxxx'> 问题在于点击iframe中文件之后无法在iframe监听事件,ctrl+p 显示空白
3.使用pdf.js
到 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'
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内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论