视频及JSON数据的导出并压缩

发布于:2024-12-20 ⋅ 阅读:(154) ⋅ 点赞:(0)

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 }); // 添加视频文件到zip
            cache[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文件到zip
            resolve(); // 没有异步操作,所以直接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();
    });
},


网站公告

今日签到

点亮在社区的每一天
去签到