vue 后台返回的文件流进行预览_vue项目-pdf预览和下载,后台返回文件流形式
背景:正好最近碰到了這種需求,記錄下來,方便以后查看。
后端返回的文件流數據如下圖所示:
后臺返回數據.png
一、pdf的預覽
一開始的時候百度了很多方法,有建議用pdfJs插件的,有iframe嵌套實現的,最后發現了一種及其簡便的實現方法:
pdfPreview(url){
this.$http({
url: `account/registerOpen/${url}`,
method: 'get',
responseType: 'arraybuffer', //一定要設置響應類型,否則頁面會是空白pdf
params: { accountId: id, lang: 'en_US' }
}).then(res => {
const binaryData = [];
binaryData.push(res);
//獲取blob鏈接
this.pdfUrl = window.URL.createObjectURL(new Blob(binaryData, { type: 'application/pdf' }));
window.open(this.pdfUrl);
}
});
}
}
二、pdf的下載
下載也挺簡單的,代碼如下:
pdfDownload(url){
const id = sessionStorage.getItem('idPdf').replace(/"/g, '');
this.$http({
url: `account/registerOpen/${url}`,
method: 'get',
responseType: 'arraybuffer',
params: { accountId: id, lang: 'en_US' }
}).then(res => {
// 下載pdf
if (url === 'PerPdf/download' || url === 'PerCrsPdf/download' || url === 'PerWbenContractPdf/download') {
//type類型可以設置為文本類型,這里是pdf類型
this.pdfUrl = window.URL.createObjectURL(new Blob([res], { type: `application/pdf` }));
const fname = `個人開戶資料`; // 下載文件的名字
const link = document.createElement('a');
link.href = this.pdfUrl;
link.setAttribute('download', fname);
document.body.appendChild(link);
link.click();
}
});
}
總結
以上是生活随笔為你收集整理的vue 后台返回的文件流进行预览_vue项目-pdf预览和下载,后台返回文件流形式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 为什么有些xpath绝对路径拿不到数据_
- 下一篇: python的最大绘图速度_Python