问题描述
在做文件下载时,从后端获取到的是文件流(HttpResponseMessage)
解决方法
使用 Blob 解决
直接上代码
export const exportnotice = (data) => {
return request({
method:"post",
url:"后端请求路径",
data,
responseType: 'blob' //必须加,否则可能出现乱码或者文件错误,导致文件无法打开
})
}
async exportList() {
let res = await exportnotice(this.formData);
const blob = new Blob([res.data]);
const fileName = "ceshi.xlsx";
if ("download" in document.createElement("a")) {
// 非IE下载
const elink = document.createElement("a");
elink.download = fileName;
elink.style.display = "none";
elink.href = URL.createObjectURL(blob);
document.body.appendChild(elink);
elink.click();
URL.revokeObjectURL(elink.href); // 释放URL 对象
document.body.removeChild(elink);
} else {
// IE10+下载
navigator.msSaveBlob(blob, fileName);
}
},
上述代码根据自己的项目具体情况修改