Vue 批量打包下载图片

参考链接:js批量打包下载图片

依赖包:FileSaver.js【下载文件】,JSZip【打包】

安装依赖:
npm install file-saver --save
npm install jszip --save

为了保证代码的复用性,故将打包下载过程封装成一个js

zipDownImage.js

import JSZip from 'jszip'
import FileSaver from "file-saver"

/**
 *
 * @class UnpackAndDownImage
 * @example
 * ```javascript
 *
 * new UnpackAndDownImage({
 *  imgSrcList: imgSrcList, // 图片资源集合
 *  onProgress(res) {
 *    
 *  },
 *  onSuccess(res) {
 * 
 *  },
 *  onError(err) {
 * 
 *  }
 * })
 *
 * ```
 */

class UnpackAndDownImage {

  constructor(option){
    const opt = {
      imgSrcList:[], // 图片资源集合
      imgBase64:[], // 图片base64集合
      imageSuffix: [], // 图片后缀
      imgName:[], // 下载后的图片名称集合
      scheduleMsg:'', // 下载进度
      errorMsg:"" , //异常信息
      onProgress: this.onProgress,
      onSuccess: this.onSuccess,
      onError: this.onError,
    }

    this.option = Object.assign({}, opt, option)

    this.start()
  }

  start(){
    let count = 0;
    
    this.option.imgSrcList.forEach(item=>{
      let suffix = item.substring(item.lastIndexOf("."));
      let imgFileName = item.substring(item.lastIndexOf("/"),item.lastIndexOf("."));
      this.option.imageSuffix.push(suffix);
      this.option.imgName.push(imgFileName)
      this.getBase64(item).then((base64)=>{
        this.option.imgBase64.push(base64.substring(22));
        count+=1
        this.option.scheduleMsg = count + '/' + this.option.imgSrcList.length

        this.option.onProgress&&this.option.onProgress(this.option.scheduleMsg)
      }).catch(err=>{
        console.log(err)
        this.option.onError&&this.option.onError(err)
      })
    })
    this.zipSaveFile()
  }

  //传入图片路径,返回base64
  getBase64(img) {
    return new Promise((resolve,reject)=>{
      const image = new Image();
      image.crossOrigin = 'Anonymous';
      image.src = img;
      if(img){
        image.onload =()=>{
          return resolve(this.getBase64Image(image)) //将base64传给done上传处理
        }
      }else{
        reject("转换base64失败")
      }
    })
  }

  getBase64Image(img, width, height) {
    //width、height调用时传入具体像素值,控制大小 ,不传则默认图像大小
    let canvas = document.createElement("canvas");
    canvas.width = width ? width : img.width;
    canvas.height = height ? height : img.height;
    let ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
    let dataURL = canvas.toDataURL("image/jpeg", 0.9);
    return dataURL;
  }

  /** 打包并下载 */
  zipSaveFile(){
    let zip = new JSZip();
    // zip.file("readme.txt", "案件详情资料\n");
    let img = zip.folder("images");
    setTimeout(()=>{
      if(this.option.imgSrcList.length == this.option.imgBase64.length){
        this.option.imgSrcList.forEach((imgItem,i)=>{
          img.file(this.option.imgName[i] + this.option.imageSuffix[i], this.option.imgBase64[i], {base64: true})
        })
        zip.generateAsync({type:"blob"}).then((content)=> {

          let fileName = String(new Date().getTime()) +'.zip'
          // see FileSaver.js
          status = saveAs(content, fileName);
          
          this.option.onSuccess&&this.option.onSuccess()

          this.option.scheduleMsg = ""
        });
      }else{
        this.zipSaveFile();
      }
   },100);
  }

  onProgress(res) {
    console.log('onProgress',
      res);
  }

  onSuccess(res) {
    console.log('onSuccess:',
      res)
  }

  onError(res) {
    console.error('onError',
      res)
  }

}

export default UnpackAndDownImage;

vue 文件使用

import UnpackAndDownImage from '@/utils/zipDownImage'

// 下载
    download(scope){
      const _this = this
      // 图片链接
      _this.imgSrcList =["http://sktcm.oss-cn-hangzhou.aliyuncs.com/files/12/3rn521778998397.jpeg",
   "http://sktcm.oss-cn-hangzhou.aliyuncs.com/files/12/3re521777382739.jpeg",
   "http://sktcm.oss-cn-hangzhou.aliyuncs.com/files/12/3pu521710268997.jpeg"]

        _this.downloadState = true

        new UnpackAndDownImage({
          imgSrcList: _this.imgSrcList,
          onError(err) {
            console.log(err)
          },
          onProgress(res) {
            console.log('onProgress',res)
          },
          onSuccess(res) {
            console.log('onSuccess',res)
          }

    },
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值