vue3实现文件批量下载并打包成zip文件

138 阅读1分钟

需要借助jszip,file-saver這两个庫

import JSZip from "jszip";
import FileSaver from "file-saver";

const getFile = (url) => {
  return new Promise((resolve, reject) => {
    // 通过请求获取文件blob格式
    let xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET", url, true);
    xmlhttp.responseType = "blob";
    xmlhttp.onload = () => {
      if (xmlhttp.status == 200) {
        resolve(xmlhttp.response);
      } else {
        reject(xmlhttp.status);
      }
    };
    xmlhttp.send();
  });
};

export const downloadZip = (fileList, zpiName = "附件") => {
  const zip = new JSZip();
  const promiess = [];
  fileList.forEach((item) => {
    const reqList = getFile(item.filePath, item.fileName).then((res) => {
      zip.file(item.fileName, res, { binary: true });
    });
    promiess.push(reqList);
  });
  Promise.all(promiess).then(() => {
    zip
      .generateAsync({ type: "blob" })
      .then((content) => {
        FileSaver.saveAs(content, zpiName);
      })
      .catch(() => {
        // window.$message.error('文件压缩失败')
      });
  });
};

凑字数凑字数凑字数凑字数凑字数凑字数凑字数凑字数凑字数凑字数