最近一个需求是批量下载文件,最后打包成zip包,post请求,
因为是文件流下载,所以在取后台数据的时候,要多传递一个【responseType: ‘blob’】这个参数
download() {
this.tableLoading = true;
console.log(this.selectionLen);
let docIds = [];
this.selectionLen.forEach((item, index) => {
docIds.push(item.id);
});
let params = {
zipName: "downloadFile",
ids: docIds,
company: this.userinfo.account_name
}; axios({
// 用axios发送post请求
method: "post",
url:
"http://xxx/pm/project/deliverable/download/zip", // 请求地址
data: params, // 参数
headers: {
"content-type": "application/json; charset=utf-8"
},
responseType: "blob" // 表明返回服务器返回的数据类型
}).then(res => {
this.tableLoading = false;
this.downloadFile(res.data);
});
},
downloadFile(data) {
let blob = new Blob([data], { type: "application/zip" });
let url = window.URL.createObjectURL(blob);
const link = document.createElement("a"); // 创建a标签
link.href = url;
let date = new Date();
link.download = "fileDown" + FormatTime("YYYY-mm-dd HH:MM", date); // 重命名文件
link.click();
URL.revokeObjectURL(url); // 释放内存
}
最后成功下载文件