PDF在線預覽
前面介紹過使用a標簽實現pdf的預覽,需要借助於瀏覽器,現在項目中需要在當前頁的彈窗中預覽PDF:

這個時候,a標簽是不滿足需求的,我們需要借助一個PDF插件:
PDF插件下載 提取碼(y5yr)
使用:
1,將PDF插件放在項目里面,或者服務器中
2,獲取PDF文件流

3,文件展示

文件下載(返回數據流)
1,無token驗證的get方法:

2,帶token驗證的方法:

let headers = { token: sessionStorage.getItem('token'), operationLocation: '*****' }; axios({ method:'post', url:window.config.host +'****', data:params, responseType:'arraybuffer', headers:headers }).then((response) => { let blob = new Blob([response.data], { type: 'application/vnd.ms-excel;charset=utf-8' }); this.content = response.data; // 漢子解碼 let filename = decodeURIComponent(response.headers['content-disposition']); if (window.navigator.msSaveOrOpenBlob) { navigator.msSaveBlob(blob, filename); } else { let aTag = document.createElement('a'); aTag.download = filename; aTag.href = window.URL.createObjectURL(blob); aTag.click(); URL.revokeObjectURL(aTag.href); } })
預覽地址下載
圖片、pdf等文件,瀏覽器會默認執行預覽,不能調用download方法進行下載,需要先把圖片、pdf等文件轉成blob,再調用download方法進行下載,轉換的方式是使用axios請求對應的鏈接

download(link, name) { if (!name) { //如果沒有提供名字,從給的Link中截取最后一坨 name = link.slice(link.lastIndexOf('/') + 1) } let eleLink = document.createElement('a') eleLink.download = name eleLink.style.display = 'none' eleLink.href = link document.body.appendChild(eleLink) eleLink.click() document.body.removeChild(eleLink) }, exportImg() { let link = "http:********r.png"; let fileName = '測試圖片下載'; axios.request({ url: link, responseType: 'blob' //關鍵代碼,讓axios把響應改成blob }).then(res => { const link = URL.createObjectURL(res.data) this.download(link, fileName) }) },
自定義下載內容
獲取頁面中的文字進行自定義下載
downloadFile(name, content) { if (typeof name == 'undefined') { throw new Error('The first parameter name is a must') } if (typeof content == 'undefined') { throw new Error('The second parameter content is a must') } if (!(content instanceof Blob)) { content = new Blob([content]) } const link = URL.createObjectURL(content) this.download(link, name) }, download(link, name) { if (!name) { //如果沒有提供名字,從給的Link中截取最后一坨 name = link.slice(link.lastIndexOf('/') + 1) } let eleLink = document.createElement('a') eleLink.download = name eleLink.style.display = 'none' eleLink.href = link document.body.appendChild(eleLink) eleLink.click() document.body.removeChild(eleLink) }, demo() { this.downloadFile('1.txt', 'lalalallalalla') this.downloadFile('1.json', JSON.stringify({ name: 'hahahha' })) },
