vue+file-saver+jszip实现批量导出图片

1、安装jszip、file-saver
npm i file-saver
npm i jszip

2、封装common.js

import JSZip from 'jszip'
import FileSaver from "file-saver";
import {
  Message
} from 'element-ui'

export function filesToRar(arrImages, filename) {
  let _this = this;
  let zip = new JSZip();
  let cache = {};
  let promises = [];
  let title = '正在加载压缩文件';

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

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

//获取文件blob
export function 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、页面引入并引用

import {
  filesToRar,
  getImgArrayBuffer
} from '@/utils/commonMethods'


// 批量导出头像
    batchAvatar() {
      if (this.multipleSelection && this.multipleSelection.length !== 0) {
        // 导出所选择用户头像
        let obj = this.throughData(this.multipleSelection)
        // console.log(img)
        filesToRar(obj, '批量压缩头像文件')
      } 
      }
    },

    throughData(arr) {
      let img = []
      arr.map(val => {
        if (val.headImg !== '') {
          let temp = {
            renameFileName: val.number + '_' +
              val.name + '.jpg',
            fileUrl: 'http://xxxxxxxxx.com/' + val.headImg
          }
          img.push(temp)
        }
      })
      return img
    }

推荐阅读更多精彩内容