import axios from "axios"; import { saveAs } from "file-saver"; import JSZip from "jszip"; async handleDownload(row) { let params = { id: row.id, }; let fileInfos = await this.getFileInfos(params); if (fileInfos .length > 0) { const zip = new JSZip(); const cache = {}; const promises = []; fileInfos .forEach((item) => { if (item.url) { const promise = this.download(item.url).then((data) => { // 下载文件, 并存成ArrayBuffer对象 zip.file(item.packageName, data, { binary: true }); // 逐个添加文件 cache[item.packageName] = data; //可要可不要 用来打印查检查添加了那些文件 }); promises.push(promise); //加到promises队列里 } else { this.$Notice.warning({ title: `附件${item.packageName}地址错误,下载失败`, }); } }); Promise.all(promises) .then(() => { //异步队列全部完成时 执行下面代码 zip.generateAsync({ type: "blob" }).then((content) => { // 生成二进制流s saveAs(content, "打包下载.zip"); // 利用file-saver保存文件 }); }) .catch((res) => { this.$Notice.warning({ title: "文件压缩失败", }); }); } }, download(href) { return new Promise((resolve, reject) => { axios({ method: "get", url: href, responseType: "arraybuffer", }) .then((data) => { resolve(data.data); }) .catch((error) => { reject(error.toString()); }); }); }, // 获取文件列表 getFileInfos(params) { return new Promise((resolve) => { axios.get("xxxxxxxx", { params: params }) .then((res) => { const result = res.data; if (result.code === "000000") { const data = result.data.fileInfos; resolve(data); } }); }); },
标签:文件,axios,const,item,params,压缩包,data,下载 From: https://www.cnblogs.com/ysx215/p/18617112