1.下载文件的api接口,在api.js中书写
export const downloadFiles= (params) => {
return axios.post(`${baseUrl}/downloadFiles`, params, {
responseType: "blob",
});
};
2.调用api接口,在需要使用下载的方法中书写,使用async和await异步加载的方式
let res = await downloadFiles(id)
//省略处理name和type的代码
//...
//name为文件名,type为文件格式
exportFile(res.data, name, type);
3.exportFile函数
function exportFile(data, filename, ext = "xlsx", type = "application/vnd.ms-excel") {
let blob = new Blob([data], { type });
if (window.navigator.msSaveBlob) {
try {
// ie浏览器自带下载文件的方法
window.navigator.msSaveBlob(data, filename);
} catch (e) {
console.log(e);
}
} else {
let elink = document.createElement("a");
elink.download = filename + "." + ext;
elink.style.display = "none";
let href = window.URL.createObjectURL(blob);
elink.href = href;
document.body.appendChild(elink);
elink.click();
document.body.removeChild(elink);
window.URL.revokeObjectURL(href); // 释放掉blob对象
}
}
标签:axios,elink,二进制,data,window,let,blob,type,下载
From: https://www.cnblogs.com/guozhiqiang/p/18519710