文件下载功能
一、文件下载
Axios({
method:'get',
url:"",
params;{},
responseType: "arraybuffer"
}).then((response) => {
console.log(response);
//headers请求头的乱码数据转换为中文
const fileName = decodeURI(
response.headers["content-disposition"].split(";")[1].split("=")[1]
);
debugger;
//下载文件
let blob = new Blob([response.data], {
type: "application/vnd.ms-excel",
});
let objectUrl = URL.createObjectURL(blob); // 创建URL
const link = document.createElement("a");
link.href = objectUrl;
// link.download = '.xlsx'// 自定义文件名
//这里是获取后台传过来的文件名
link.setAttribute("download", fileName);
link.click(); // 下载文件
URL.revokeObjectURL(objectUrl); // 释放内存
})
.catch((error) => {
console.log(error);
alert("下载失败");
});
注意:
请求头需要改为 “arraybuffer” 并使用 Blob 构造函数创建二进制对象
否则下载的文件无法打开,或打开报错。