0
点赞
收藏
分享

微信扫一扫

前端下载二进制流文件 为 excel文件


需求: 前端请求后端接口,后端返回二进制流,前端需实现浏览器自动下载成excel文件。

原理: 通过a标签的href属性将二进制数据转换为excel文件,再通过download属性将文件下载到本地。
注意: 接口响应的数据类型要设置为blob类型

// 下载导入用户的模板
export function downloadTemplate() {
return request({
url: 'api/users/excel',
method: 'get',
responseType: 'blob'
});
}

实现代码:

// 下载模板
downloadTemplate() {
try {
crudUser.downloadTemplate().then((res) => {
this.filename = '导入员工模板.xlsx';
this.url = window.URL.createObjectURL(res);
const link = document.createElement('a');
link.style.display = 'none';
link.href = this.url;
link.setAttribute('download', this.filename);
document.documentElement.appendChild(link);
link.click();
document.documentElement.removeChild(link);
});
} catch (error) {
console.warn('下载模板出错!', error);
}
}

记得三连~


举报

相关推荐

0 条评论