vue前端导出zip包

需求:将多个文件打包成zip压缩包下载的功能

以下是后台返回的需要下载的文件的数据结构:

//zipName是zip压缩包的名字,fileUrl是需要下载的文件地址,fileName是文件的名称

{
    "status": 1,
    "message": "导出成功",
    "data": {
        "zipName": "全部简历.zip",
        "filesArr": [ {
            "fileUrl": "https://xxxxxx",
            "fileName": "张亮的简历.pdf"
        }, {
            "fileUrl": "https://xxxxxx",
            "fileName": "小明的简历.pdf"
        }, {
            "fileUrl": "https://xxxxxx",
            "fileName": "张三.pdf"
        }]
    }
}

 

第一步:下载插件

//jszip是一个用于创建、读取和编辑.zip文件的JavaScript库 可以将文件或者图片打包成一个Zip文件。
npm install jszip

//前端下载, 基于Blob进行下载,
npm install file-saver

 

第二步:在需要用以上插件的页面中引入:

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

 

第三步:调用代码

     /***
       * 文件打包
       * filesArr: 需要打包的数据集合:[{fileUrl:文件url, fileName:文件名}]
       * fileName: 压缩包名称
       */
      filesToRar(filesArr, zipName) {
        let _this = this;
        let zip = new JSZip();
        let cache = {};
        let promises = [];
        _this.title = "正在加载压缩文件";
        this.loading = true;
        this.loadingText = _this.title;
        for (let i = 0, len = filesArr.length; i < len; i++) {
          let item = filesArr[i];
          const promise = _this.getFileArrayBuffer(item.fileUrl).then((data) => {
            // 下载文件, 并存储为ArrayBuffer对象(blob)
            // 逐个添加文件
            zip.file(item.zipName, data, { binary: true });
            cache[item.zipName] = data;
            this.loadingText = _this.title + "  " + filesArr.length + " / " + i;
          });
          promises.push(promise);
        }

        Promise.all(promises)
          .then(() => {
            zip.generateAsync({ type: "blob" }).then((content) => {
              _this.title = "正在压缩";
              this.loadingText = _this.title;
              // 生成二进制流
              // 利用file-saver保存文件,自定义文件名
              FileSaver.saveAs(content, fileName);
              _this.title = "压缩完成";
              this.loadingText = _this.title;
              this.loading = false;
            });
          })
          .catch((res) => {
            this.loading = false;
            _this.$message.error("文件压缩失败");
          });
      },





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

 

posted @ 2022-03-07 16:55  最初的样子  阅读(2594)  评论(1编辑  收藏  举报