您的位置:首页 > Web前端 > Vue.js

vue项目-pdf预览和下载,后台返回文件流形式

2020-02-05 21:52 4906 查看

背景:正好最近碰到了这种需求,记录下来,方便以后查看。

后端返回的文件流数据如下图所示:

一、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();
}
});
}
  • 点赞
  • 收藏
  • 分享
  • 文章举报
不知道叫啥... 发布了6 篇原创文章 · 获赞 2 · 访问量 124 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: