前端玩玩--一次性打包下载多个文件

155 阅读1分钟

使用jszip与file-saver 结合fetch在前端进行下载,适合批量下载,只触发一次下载,不会拦截。

import { VXETable } from 'vxe-table';
import axios from "@/utils/request";
import { downloadFileConfig, fileServe } from '@/utils/config';
import JSZip from "jszip";
import { saveAs } from "file-saver";

// 下载附件
const downloadFile = async(row : any) => {
    let fileList = JSON.parse(row.files);
    if (fileList.length === 1) {
        let fileName = fileList[0].name;
        let fileNameArr = fileName.split(".");
        let fileId = fileList[0].id;
        let downUrl = `${fileServe.host}` + `${downloadFileConfig.host}` + '?fid=' + fileId;

        // 请求文件
        fetch(downUrl, {
            method: 'get',
            credentials: "include" // 允许 cookie 共享
        }).then(response => 
            response.blob()).then(blob => {
                // 下载到本地
                VXETable.saveFile({ filename: fileNameArr[0], type: fileNameArr[fileNameArr.length - 1], content: blob })
            }
        )
    } else if (fileList.length > 1) {
        const zip = new JSZip();
        for (const file of fileList) {
            let fileName = file.name;
            let fileId = file.id;
            let downUrl = `${fileServe.host}` + `${downloadFileConfig.host}` + '?fid=' + fileId;

            // 请求文件
            const response = await fetch(downUrl, { method: 'get', credentials: "include" })
            const blob = await response.blob();
            console.log(fileName + "----文件大小:", blob.size);
            zip.file(fileName, blob); // 添加到 ZIP
        }
        zip.generateAsync({ type: "blob" }).then((content) => {
            console.log(content);
            saveAs(content, "多附件下载包.zip"); // 触发 ZIP 下载
        });
    }
}

export { deleteFile, downloadFile }