npm下载安装 jszip 和 file-saver 这两个库来实现文件的压缩和保存功能:
npm install jszip
npm install file-saver
导入依赖库:
import JSZip from 'jszip';
import { saveAs } from 'file-saver';
方法实现:
batchDownload() {const zip = new JSZip();// 下载后压缩包的名称const blogTitle = '检测数据.zip';const cache = {};const promises = [];// this.tableData 为数据体数据this.tableData.forEach(item => {// URL 构建修正let url = "https://plat.aiplusfirst.com" + (item.wuImg ? item.wuImg : item.img);// 文件名构建const folderName = item.id + "-" + item.quadrant + '-' + item.leftRightBreasts + '-' +this.classifyToNumber(item.aiResult) + '-' + this.classifyToNumber(item.allResult) +'-' + item.contFlag + '-' + item.deviceNum;const video_name = folderName + '/' + item.id + '.' + item.imgType;const json_name = folderName + '/' + item.id + '.json';// 获取并存储视频文件const videoPromise = this.getFile(url).then(data => {zip.file(video_name, data, { binary: true }); // 添加视频文件到zipcache[video_name] = data;});// 处理JSON数据const jsonData = JSON.stringify(item.jsonData);const jsonBlob = new Blob([jsonData], {type: 'application/json'});const jsonPromise = new Promise(resolve => {zip.file(json_name, jsonBlob); // 添加JSON文件到zipresolve(); // 没有异步操作,所以直接resolve});// 将两个Promise都推入数组promises.push(videoPromise, jsonPromise);});// 等待所有Promise完成Promise.all(promises).then(() => {zip.generateAsync({type: "blob",compression: 'DEFLATE',compressionOptions: {level: 9 // 压缩等级}}).then(content => {saveAs(content, blogTitle); // 保存压缩包});}).catch(error => {console.error('批量下载失败:', error);});
},getFile(url) {return new Promise((resolve, reject) => {let xmlHttp = new XMLHttpRequest();xmlHttp.open("GET", url, true);xmlHttp.responseType = "blob";xmlHttp.onload = function () {if (xmlHttp.status === 200) {resolve(xmlHttp.response);} else {reject(xmlHttp.statusText || xmlHttp.responseText);}};xmlHttp.onerror = function () {reject(xmlHttp.statusText || xmlHttp.responseText);};xmlHttp.send();});
},