最近一個需求是批量下載文件,最后打包成zip包,post請求,
因為是文件流下載,所以在取后台數據的時候,要多傳遞一個【responseType: ‘blob’】這個參數
1 download() { 2 this.tableLoading = true; 3 console.log(this.selectionLen); 4 let docIds = []; 5 this.selectionLen.forEach((item, index) => { 6 docIds.push(item.id); 7 }); 8 let params = { 9 zipName: "downloadFile", 10 ids: docIds, 11 company: this.userinfo.account_name 12 }; 13 14 axios({ 15 // 用axios發送post請求 16 method: "post", 17 url: 18 "http://xxx/pm/project/deliverable/download/zip", // 請求地址 19 data: params, // 參數 20 headers: { 21 "content-type": "application/json; charset=utf-8" 22 }, 23 responseType: "blob" // 表明返回服務器返回的數據類型 24 }).then(res => { 25 this.tableLoading = false; 26 this.downloadFile(res.data); 27 }); 28 },
1 downloadFile(data) { 2 let blob = new Blob([data], { type: "application/zip" }); 3 let url = window.URL.createObjectURL(blob); 4 const link = document.createElement("a"); // 創建a標簽 5 link.href = url; 6 let date = new Date(); 7 link.download = "fileDown" + FormatTime("YYYY-mm-dd HH:MM", date); // 重命名文件 8 link.click(); 9 URL.revokeObjectURL(url); // 釋放內存 10 }
最后成功下載文件