vue 项目图片批量导出并压缩成zip

1、安装依赖并引入

  npm install jszip --save

  npm install file-saver --save

  import JSZip from 'jszip'   import FileSaver from 'file-saver' 2、将远程或本地图片的url转换成base64,然后下载
 /**
   *多个图片压缩成zip导出
   */
 private downloadZip() {
   let that = this
   const zip = new JSZip()
   let arrs:any = [] // 这个数组只用于判断图片是否都转换成base64
   setTimeout(_ => {
     let arr = that.multipleSelections // 待转换的数据(包含图片的名和地址)
     arr.forEach((item:any) => {
       let fileName = item.orgName // 图片那么
       let url = ''
       // item.shareImg 是图片地址
       that.getBase64(item.shareImg, (dataURL:any) => {
         url = dataURL // 图片url转换成base64
         zip.file(fileName + '.png', url.substring(22), { base64: true })
         arrs.push(url)
         if (arrs.length === that.multipleSelections.length) { // 若要导出的图片全部转换为base64了,则开始导出
           zip.generateAsync({ type: 'blob' }).then(content => {
             FileSaver.saveAs(content, '二维码.zip')
           })
         }
       })
     })
   }, 0)
 }
 // 图片url转换成base64
 private getBase64(url:string, callback:any) {
   var Img = new Image()
   var dataURL = ''
   Img.src = url + '?v=' + Math.random()
   Img.setAttribute('crossOrigin', 'Anonymous')
   Img.onload = function() {
     var canvas:any = document.createElement('canvas')
     var width = Img.width
     var height = Img.height
     canvas.width = width
     canvas.height = height
     canvas.getContext('2d').drawImage(Img, 0, 0, width, height)
     dataURL = canvas.toDataURL('image/jpeg')
     return callback ? callback(dataURL) : null
   }
 }

 JSzip API地址:https://stuk.github.io/jszip/documentation/api_jszip/constructor.html

 

   
上一篇:[AWS] Solve Error: Uploaded file must be a non-empty zip


下一篇:js压缩文件或文件夹