使用iframe實現pdf文件預覽功能
本文主要介紹使用iframe預覽pdf的功能,以及iframe預覽報錯問題和iframe未能加載PDF文檔。
預覽自帶分頁、下載、旋轉、比例等功能。
一、iframe是什么
iframe的介紹:將src的內容規(guī)定在 中顯示出。
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) // }) }, }
2.圖文詳解
3.錯誤情況
原因:說明你createObjectURL讀的不是設置responseType: 'blob’后獲取的Blob,可能是直接讀的后端返回的那個看不懂的文件流res
到此這篇關于使用iframe實現pdf文件預覽功能的文章就介紹到這了,更多相關iframe pdf內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Bootstrap優(yōu)化站點資源、響應式圖片、傳送帶使用詳解3
這篇文章主要介紹了Bootstrap優(yōu)化站點資源、完成響應式圖片、讓傳送帶支持手勢的相關知識,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-10-10JS/HTML5游戲常用算法之碰撞檢測 像素檢測算法實例詳解
這篇文章主要介紹了JS/HTML5游戲常用算法之碰撞檢測 像素檢測算法,結合實例形式詳細分析了javascript像素檢測碰撞算法的原理、實現步驟及相關操作技巧,需要的朋友可以參考下2018-12-12