欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 前端技术 > vue >内容正文

vue

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

发布时间:2025/4/16 vue 97 豆豆
生活随笔 收集整理的这篇文章主要介绍了 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预览和下载,后台返回文件流形式的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。