0002-Vue下载图片并打包成压缩文件

一、安装需要的包: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 );
      },

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值