图片下载功能(base64)

兼容各个浏览器下载图片

  1. 图片来源是线上地址
  2. 图片来源是项目的静态资源
  3. 图片来源是Blob类型

思路:讲图片转为 base64 借用 a 标签的downloan 属性进行下载

静态路径图片转为base64

/**
   * 静态路径图片转为base64
   * @param {*} imgUrl 图片路径
   */
  img2Base64:function(imgUrl){
    return new Promise((resolve,reject)=>{
      const image = new Image();
      // 解决跨域 canvas 污染问题
      image.setAttribute("crossOrigin", "");
      image.src = imgUrl;
      image.onload = function() {
        const canvas = document.createElement("canvas");
        canvas.width = image.width;
        canvas.height = image.height;
        const context = canvas.getContext("2d");
        context.drawImage(image, 0, 0, image.width, image.height);
        resolve(canvas.toDataURL())
      }
    })
  },

 

blob类型的图片转为base64

/**
   * blob类型的图片转为base64
   * @param {*} blob  图片流
   */
  blob2Base64:function(blob){
    return new Promise((resolve,reject)=>{
      let oFileReader = new FileReader();
      oFileReader.onloadend = function (e) {
        let base64 = e.target.result;
        resolve(base64);
      };
      oFileReader.readAsDataURL(blob);
    })
  },

然后见文件下载即可。

downLoadImage:function(base64,imgName){
    let browser = Utils.whichBrowser();
    if (window.navigator.msSaveOrOpenBlob) {
      var bstr = atob(base64.split(',')[1])
      var n = bstr.length
      var u8arr = new Uint8Array(n)
      while (n--) {
       u8arr[n] = bstr.charCodeAt(n)
      }
      var blob = new Blob([u8arr])
      window.navigator.msSaveOrOpenBlob(blob, imgName + '.png');
     }else{
      var a = document.createElement('a')
      if (typeof a.download === 'undefined') {
        window.location = base64
      } else {
        a.href = base64
        a.download = browser=="FF" ? imgName + '.png' : imgName;
        document.body.appendChild(a)
        a.click()
        a.remove()
      }
    }
  },

你可能感兴趣的:(JS)