vue中axios使用post请求下载文件中文乱码
1、首先我们需要单独封装或者自己在新建axios的时候,需要加上:responseType: "blob", 例如:
let param = Object.assign({}, this.form, { pageIndex: "1", pageSize: "1000", }); axios({ method: "post", url:axios.defaults.baseM3URL+ "/find/logs/export", responseType: "blob", data: param, }).then((res) => {})
2、当前这样做还是远远不够滴,blob的默认编码方式是utf-8,所以就算我们下载下来文档,中文还是乱码的,我们需要将其转换为gbk格式,如何转换呢?在接口请求的出参的最前面加上\ufeff,下面是全部代码仅供参考,亲测有效哦
startDownload() {
let param = Object.assign({}, this.form, {
pageIndex: "1",
pageSize: "1000",
});
axios({
method: "post",
url:axios.defaults.baseM3URL+ "/find/logs/export",
responseType: "blob",
data: param,
}).then((res) => {
debugger
let today = new Date();
let tadayDate =
today.getFullYear() +
"-" +
(today.getMonth() + 1) +
"-" +
today.getDate();
const fileName = "日志查询-" + tadayDate + ".csv";
let resdata = "\ufeff" + res.data;
let blob = new Blob([resdata], { type: 'text/csv,charset=UTF-8'});
if (window.navigator.msSaveOrOpenBlob) {
//msSaveOrOpenBlob方法返回bool值
navigator.msSaveBlob(blob, fileName); //本地保存
} else {
var link = document.createElement("a"); //a标签下载
link.href = window.URL.createObjectURL(blob);
link.download = fileName;
link.click();
window.URL.revokeObjectURL(link.href);
}
})
},
每天将自己工作和学习中遇到的问题和好的方法写下来,作为积累,养成一个好习惯,从此刻开始~