请求:
// 下载单个文件
export function commonFileDownloads(query) {
return request({
url: `url`,
method: "GET",
responseType: "arraybuffer", // 设置axios接收的类型
});
}
代码:
//下载附件
async downLoadFile(annexAddr) {
this.is_tijiao = true;
let res = await commonFileDownloads(annexAddr);//拿到后端返回的二进制文件流以及文件名+类型
let stringName = res.headers["content-disposition"].split(";")[1]; //一般来说,文件名字后端都在返回头里,前后端可以约定文件名前用 @ 符号分隔,便于取值,用其他符号也可以。
let fileNameEnd = stringName.split(".")[1]; //获取到了后缀名
let fileName = stringName.split(".")[0].slice(9); //获取到文件名(不含后缀)
fileName = decodeURIComponent(fileName); //一般来说后端返回的名字没有转码,需要前端解码utf-8,如果后端转了,就不用转。
let endFileName = `${decodeURIComponent(fileName) + "." + fileNameEnd}`;
let blob = new Blob([res.data], { type: "application/zip" }); //application/zip就是设置下载类型,需要设置什么类型可在标题二处查看,
const url = window.URL.createObjectURL(blob); //设置路径
const link = window.document.createElement("a"); // 创建a标签
link.href = url;
link.setAttribute("download", endFileName); // 给下载后的文件命名
link.style.display = "none";
link.click();
URL.revokeObjectURL(url); // 释放内存
this.is_tijiao = false;
},