axios 下载方式有两种
两种方法分别适用于不同的数据返回格式
, 通常也就这2种格式.
方法一
如果请求地址返回的数据是就是一个文件file,那么使用方法一,模拟浏览器下载文件
// 使用get方法下载
async handleExport() {
const params = {
hotelName: this.formData.hotelName,
deviceMac: this.formData.deviceMac,
roomNumber: this.formData.roomNumber
};
// axios.get( url地址,params参数)
const response = await axios.get(baseURL + exportBillExcel, {
params: params
});
// 通过模仿浏览器跳转来下载
const responseParam = [];
for (const item in response.config.responseParam) {
responseParam.push(`${item}=${response.config.responseParam[item]}`);
}
const url = responseParam.length ? `${response.config.url}?${responseParam.join('&')}` : `${response.config.url}`;
window.location.href = url;
},
方法二
如果请求地址返回的数据是数据流的格式,那么使用方法二,前端对接收到的数据进行再处理,同时要求请求返回的数据header中包含文件名.
// 使用get方法下载
async handleExport() {
const params = {
hotelName: this.formData.hotelName,
deviceMac: this.formData.deviceMac,
roomNumber: this.formData.roomNumber
};
// axios.get( url地址,params参数)
const response = await axios.get(baseURL + exportBillExcel, {
params: params
});
// 接口返回的数据,前端进行处理,将其变为file格式的excel文件
exportExcel(res.data, data);
},
/**
* 下载excel
* @param data 接口返回数据 res.data
* @param res 接口返回数据 res
* @returns excel文件
*/
export function exportExcel(data, res) {
if (!data) {
// 如果没有data数据就不进行操作
return;
}
// 获取headers中的filename文件名
const tempName = res.headers["content-disposition"]
.split(";")[1]
.split("filename=")[1];
// iconv-lite解决中文乱码
const iconv = require("iconv-lite");
iconv.skipDecodeWarning = true; // 忽略警告
const fileName = iconv.decode(tempName, "gbk");
const blob = new Blob([data], { type: "application/vnd.ms-excel" }); // 转换成二进制对象
if ("download" in document.createElement("a")) {
// 不是IE浏览器
const url = window.URL.createObjectURL(blob); // 二进制对象转换成url地址
const link = document.createElement("a");
link.style.display = "none";
link.href = url;
link.setAttribute("download", fileName);
document.body.appendChild(link);
link.click();
document.body.removeChild(link); // 下载完成移除元素
window.URL.revokeObjectURL(url); // 释放掉blob对象
} else {
window.navigator.msSaveBlob(blob, fileName);
}
}