1.封装通用请求函数,注意需要设置axios的responseType为blob
function download(url, params, filename) {
let _this = this;
_this
.$axios({
method: "post",
url: url,
data: params,
responseType: "blob"
})
.then(res => {
let data = res.data;
let fileReader = new FileReader();
// 请求成功时服务端返回blob文件流,请求失败时会返回json格式的数据,两种格式需要单独处理
fileReader.onload = function() {
try {
let jsonData = JSON.parse(this.result);
if (jsonData.code) {
return false;
}
} catch (err) {
// 解析成对象失败,说明是正常的文件流
let time = Date.now();
downLoadXls(data, `${filename}.xlsx`);
}
};
fileReader.readAsText(data);
});
}
2.处理文件流
function downLoadXls(data, filename) {
//接收的data是blob,若接收的是文件流,需要转化一下
if (typeof window.chrome !== "undefined") {
// Chrome version
var link = document.createElement("a");
link.href = window.URL.createObjectURL(data);
link.download = filename;
link.click();
} else if (typeof window.navigator.msSaveBlob !== "undefined") {
// IE
var blob = new Blob([data], {
type: "application/force-download"
});
window.navigator.msSaveBlob(blob, filename);
} else {
// Firefox
var file = new File([data], filename, {
type: "application/force-download"
});
// window.open(URL.createObjectURL(file));
}
}