文章目录
前言:
vue-pdfandroid系统定制开发也可以预览pdf,android系统定制开发但是有些情况下会预览不出来。。
本文主要介绍使用iframe预览pdf的功能,以及iframe预览报错问题和iframe未能加载PDF文档。
.
.
预览自带分页、下载、旋转、比例等功能。
.
一、是什么?
将src的内容规定在 中显示出。
iframe既可以用来预览本地static下的文档,也可以预览后端返回的文件流文档
二、使用步骤
1.使用与逻辑:
逻辑:就是将后端返回的看不懂的文件流,设置成
responseType = 'blob'
然后读取到返回的Blob,再使用createObjectURL读取出url即可
对于后缀名是大写的.PDF 没法直接预览,建议直接下载下来看
<iframe :src="url" style="border: none;width: 100%;height: 100%;"> <p>您的浏览器不支持 iframe 标签,请从列表中下载预览</p> </iframe> data () { return { url: '', } }, methods: { downLoadFileImg (fileUrl, fileName) {// 后端文件地址和名称 // 可下载,名称也有效 -- 推荐 const x = new window.XMLHttpRequest() x.open('GET', fileUrl, true) x.responseType = 'blob' // 选择返回格式为blob --- 一般后端返回的是看不懂的文件流 故需要转成blob x.onload = () => { this.url = window.URL.createObjectURL(x.response) //将后端返回的blob文件读取出url console.log('blob====',x.response) //Blob {size: 38617, type: 'application/pdf'} console.log('url====',this.url) //blob:http://localhost:7197/cb047277-e5e6-4905-bf8c-dbecd86a0105 // url可以预览和下载------如果想要下载就把下方注释打开即可 // const a = document.createElement('a') // a.href = this.url // a.download = fileName // a.click() } x.send() // // 或者下方的方式 // axios({ // url: G_CGI_PHP.superOrder.upfile + "?id=" + this.rowData.id, // method: 'get', // timeout: 100000, // responseType: 'blob', // headers: { // // "type": 'application/pdf' // }, // }).then(res => { // console.log('res.data', res.data) // this.url = window.URL.createObjectURL(res.data) //将后端返回的blob文件读取出url // console.log('通过读取blob文件得到url地址===', this.url) // }).catch(error => { // console.log(error) // }) }, }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
2.图文详解:
1.后端返回的是,如下:
2.调用后端接口,通过设置
responseType: 'blob'
,得到的Blob和读取的url如下:
3.错误情况:
3.1 iframe报未能加载PDF文档。:
3.2 如果报错:Uncaught (in promise) TypeError: Failed to execute ‘’ on ‘URL’: Overload resolution failed.
at eval
原因:说明你createObjectURL读的不是设置
responseType: 'blob'
后获取的Blob,可能是直接读的后端返回的那个看不懂的文件流res
三、参考链接
总结
iframe的预览效果更好,使用也很简单!推荐!!!