前端处理图片压缩下载

120 阅读1分钟
  import JSZip from 'jszip'
import FileSaver from 'file-saver'
downLoad() {
      let _this = this;
      let zip = new JSZip();
      let cache = {};
      let promises = [];
      // _this.title = "正在加载压缩文件";
      // this.loading = true

      for (let i=0;i<this.payVoucherArr.length;i++) {
        const item = this.payVoucherArr[i]
        try {
          let url =  item.url.replace('/supplier/images','')
          url = location.origin+url
          const temp = url.split('.')
          // 文件格式
          const appendix = temp[temp.length - 1]

          console.log(item)
          // 图片名
          const key = `付款账号:${item.code}`+'-img' + item.index+ '.' + appendix
          console.log('key', key)
          console.log(_this.getImgArrayBuffer(url))
          const promise = _this.getImgArrayBuffer(url).then((data) => {
            // 下载文件, 并存成ArrayBuffer对象(blob)
            zip.file(key, data, {binary: true}); // 逐个添加文件
            cache[key] = data;
          }).catch(e => {
            // _this.loading = false
          });
          promises.push(promise);
        } catch (e) {
          // _this.loading = false
        }
      }

      Promise.all(promises)
        .then(() => {
          zip.generateAsync({type: "blob"}).then((content) => {
            // _this.title = "正在压缩";
            // 生成二进制流
            FileSaver.saveAs(
              content,
              `服务费付款信息`
            ); // 利用file-saver保存文件  自定义文件名
            // _this.title = "压缩完成";
            _this.$message.success("下载成功");
            // _this.loading = false
          });
        }).catch((res) => {
        _this.$message.error("文件压缩失败");
        // _this.loading = false
      });
    },