首先,需要配置服务器响应的数据类型 responseType: 'blob'
download: (id) => {
return service({
url: `/personAccountBill/download/${id}`,
method: 'get',
responseType: 'blob'
});
}
利用a标签的属性实现文件下载
download: (api, id, name) => {
// api 后台接口
// id 文件id 接口参数
// name 文件名字
api.download(id).then((res) => {
let eleLink = document.createElement('a');
eleLink.setAttribute('download', name);
// eleLink.download = name;
eleLink.style.display = 'none';
eleLink.setAttribute('href', URL.createObjectURL(res.data));
// eleLink.href = URL.createObjectURL(res.data);
// 触发点击
document.body.appendChild(eleLink);
eleLink.click();
// 然后移除
document.body.removeChild(eleLink);
});
}
最后粘一个后台返回供参考
结束,拜拜。