1. 安装插件
npm install jszip
npm install file-saver
  1. 在vue文件中使用
import JSZip from'jszip'
import FileSaver from'file-saver'

2.调用方法

//通过url 转为blob格式的数据
getImgArrayBuffer(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();
      });
    },

3. 打包

// imgDataUrl 数据的url数组
BatchDownload(){
      let _this = this;
        let zip = new JSZip();
        let cache = {};
        let promises = [];
        _this.title = '正在加载压缩文件';

        for (let item of this.imgDataUrl) {
          const promise= _this.getImgArrayBuffer(item.path).then(data => {
            // 下载文件, 并存成ArrayBuffer对象(blob)
            zip.file(item.name, data, { binary: true }); // 逐个添加文件
            cache[item.name] = data;
          });
          promises.push(promise);
        }

        Promise.all(promises).then(() => {
          zip.generateAsync({ type: "blob" }).then(content => {
            _this.title = '正在压缩';
            // 生成二进制流
            FileSaver.saveAs(content, '数据包'); // 利用file-saver保存文件  自定义文件名
            _this.title = '压缩完成';
          });
        }).catch(res=>{
          _this.$message.error('文件压缩失败');
        });
    },
GitHub 加速计划 / vu / vue
103
18
下载
vuejs/vue: 是一个用于构建用户界面的 JavaScript 框架,具有简洁的语法和丰富的组件库,可以用于开发单页面应用程序和多页面应用程序。
最近提交(Master分支:1 个月前 )
9e887079 [skip ci] 1 年前
73486cb5 * chore: fix link broken Signed-off-by: snoppy <michaleli@foxmail.com> * Update packages/template-compiler/README.md [skip ci] --------- Signed-off-by: snoppy <michaleli@foxmail.com> Co-authored-by: Eduardo San Martin Morote <posva@users.noreply.github.com> 1 年前
Logo

新一代开源开发者平台 GitCode,通过集成代码托管服务、代码仓库以及可信赖的开源组件库,让开发者可以在云端进行代码托管和开发。旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐