一、安装需要的包:jszip,file-saver

yarn add jszip
yarn add file-saver

安装后的lock文件如下:

jszip@^3.1.5:
  version "3.1.5"
  resolved "https://registry.yarnpkg.com/jszip/-/jszip-3.1.5.tgz#e3c2a6c6d706ac6e603314036d43cd40beefdf37"
  dependencies:
    core-js "~2.3.0"
    es6-promise "~3.0.2"
    lie "~3.1.0"
    pako "~1.0.2"
    readable-stream "~2.0.6"

file-saver@^2.0.0-rc.4:
  version "2.0.0-rc.4"
  resolved "https://registry.yarnpkg.com/file-saver/-/file-saver-2.0.0-rc.4.tgz#aaefae8145193257050a0d92d90941516b4b759b"

二、封装下载方法

1、图片转换为base64

/**
 * 将图片转换为base64格式
 * @param image
 * @param ext
 * @returns {string}
 */
function getBase64Image(image,ext){
  let canvas = document.createElement("canvas");
  canvas.width = image.width;
  canvas.height = image.height;
  let context = canvas.getContext("2d");
  context.drawImage(image,0,0,image.width,image.height);

// 这里是不支持跨域的
  console.info('ext:', ext);
  let base64 = canvas.toDataURL(`image/${ext}`);
    base64 = base64.substring(base64.indexOf(',')+1);
  return base64;
}

2、下载方法 

/**
 *将图片打包成zip包下载
 * @param app 应用
 * @param strFileList 以逗号分隔的文件列表字符串
 * @param filename 打包后的文件名
 */
function wrapImageToZip(app,strFileList, filename){
  let that = this,
    constant = app.$store.state.constant,//常量对象
    arrImages = strFileList.split(',').filter(item=>!constant.arrEmpty.includes(item)),
    imageCount = arrImages.length,
    numCount = 0,
    arrBase64 = [];

  arrImages.map(item => {
    let url = `${constant.aliHomeURLPath}${item}?a=${new Date().getTime()}`,
      image = new Image();
    image.src = url;
    image.setAttribute("crossOrigin", '*')
    image.onload = function () {
      numCount++;
      let ext = url.substring(url.lastIndexOf(".") + 1, url.lastIndexOf('?')), base64 = that.getBase64Image(image, ext);//需要先将图片转换为base64
      arrBase64.push({ext, base64});
      if (numCount == imageCount) {
        Promise.all([
          // 下面是引入依赖包
          require('jszip'),
          import('file-saver'),
        ]).then(([JSZip, FileSaver]) => {
          let zip = new JSZip();

          let img = zip.folder('');
          for (let bItem of arrBase64.entries()) {
            img.file(`${bItem[0]}.${bItem[1].ext}`, bItem[1].base64, {base64: true});
          }
          // 图片是base64格式,但不要base64前缀
          let fileName = `${filename}.zip`;
          zip.generateAsync({type: 'blob'})
            .then(function (content) {
              // see FileSaver.js
              FileSaver.saveAs(content, fileName);
            });
        });
      }
    };
  });
}

三、 应用方法下载图片并打包成zip文件

<el-dropdown-menu>
     <el-dropdown-item @click.native="downloadFile(scope.row)">
                下载审核资料
     </el-dropdown-item>
</el-dropdown-menu>
      downloadFile(row) {
        let that = this;
        if (!row.frontPath && !row.rearPath) {
          this.$notify.info({
            title: '温馨提示',
            message: '没有资料可下载'
          })
          return false
        }

        let sendString = row.frontPath;
        if(sendString){
          sendString += ',' + row.rearPath
        }else{
          sendString = row.rearPath;
        }
        let fileName = `${that.$utils.toTimeFormat(new Date().getTime(),'YYYYMMDDhhmmssSSS')}${row.id}`;
        this.$utils.wrapImageToZip(this, sendString, fileName );
      },

 

Logo

前往低代码交流专区

更多推荐