vue中使用axios下载excel二进制文件 出现乱码问题的解决方法?
首先,先排查问题。
- 就是请求返回的类型是不是(或者有没有这个)responseType: "blob"。
- 在main.js中是否引入了和axios有冲突的插件,我当时就是因为引入了 mock, 所以这么多次都一直是乱码。
- 最后如果还是不行的话可以尝试修改 let blob = new Blob([res], {type: "application/vnd.ms-excel"}); res就是后端返回的二进制文件流。
代码如下:
testExport({ 传递的参数 })
.then((res) => {
const blob = new Blob([res], {
type: "application/vnd.ms-excel;charset=UTF-8",
});
const fileName = "下载测试文件.xls";
const alink = document.createElement("a");
alink.download = fileName;
alink.style.display = "none";
alink.href = URL.createObjectURL(blob); // 这里是将文件流转化为一个文件地址
document.body.appendChild(alink);
alink.click();
URL.revokeObjectURL(alink.href); // 释放URL 对象
document.body.removeChild(alink);
})
.catch((error) => {
this.$notify({
type: "error",
title: "网络错误,请重新查询",
message: error,
position: "bottom-right",
});
})
// 封装的请求
export function testExport(data) {
return HTTP_FUNCTION({
url: HTTP_URL.test.export,
method: "post",
data,
responseType: "blob",
});
}