- 返回值
- 得到接口返回的response, 直接传入
downloadAxios()函数
export function downloadAxios(res, filename = "", type = "office") {
if (!filename) {
let contentDispositon = "";
if (res.headers.hasOwnProperty("Content-Disposition")) {
contentDispositon = res.headers["Content-Disposition"];
} else if (res.headers.hasOwnProperty("content-disposition")) {
contentDispositon = res.headers["content-disposition"];
} else {
contentDispositon = ";filename=";
}
filename = decodeURI(contentDispositon.split(";")[1].split("=")[1]);
}
let fileType = {};
if (type == "blob") {
fileType["type"] = "blob";
} else {
fileType["type"] =
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
}
let blob = new Blob([res.data], fileType);
const aLink = document.createElement("a");
document.body.appendChild(aLink);
aLink.style.display = "none";
aLink.href = window.URL.createObjectURL(blob);
aLink.setAttribute("download", filename);
aLink.click();
document.body.removeChild(aLink);
}
- 函数调用成功后,会自动下载,页签右上角会显示,当你打开下载记录的excel表时,如果显示如下,其实是前端问题
- 设置
responseType 为 arraybuffer指定响应的数据类型为二进制数据。此外,我们还可以设置了请求头中的 Content-Type 为 application/vnd.ms-excel,以确保服务器正确识别导出的文件类型 - 确保后台正确设置了
字符编码,并且前端也正确处理了字符编码,以确保下载的 Excel 文件能够正确显示。
return request('/xxxxx/yield', {
baseURL: process.env.SERVER,
method: 'get',
params: params,
headers: { 'X-Auth-Token': getToken() },
responseType: 'arraybuffer' // 如果没有设置这个responseType,那打开excel文件就会显示如上图
});
参考文献(1)
结语
前端react QQ群:
788023830----React/Redux - 地下老英雄前端交流QQ群:
249620372----FRONT-END-JS前端(我们的宗旨是,为了加班,为了秃顶……,仰望大佬),希望小伙伴们加群一起学习