base64 转 blob,bse64转flle,blob转bse64

base64转blob:

//dataurl:base64的url  fileType:要转的文件类型 
urlToBlob (dataurl, fileType) {
     dataurl = dataurl.replace('-', '+').replace('_', '/').split(';base64,')[1] //以防生成的url字符串不规范
     // var raw = decodeURIComponent(escape(window.atob(dataurl))) // 用decodeURIComponent防止base64编码错误
     var raw = window.atob(dataurl) // 用decodeURIComponent防止base64编码错误
     var rawlength = raw.length
     var uint8array = new Uint8Array(rawlength)
     for (var i = 0; i < rawlength; i++) {
       uint8array[i] = raw.charCodeAt(i)
     }
     var blob = new Blob([uint8array], {type: 'image/' + fileType})
     return blob
   },

base64转file:

//dataurl:base64的url  filename:文件名字 
urlToFile (dataurl, filename) { // 将base64转换为文件
      var arr = dataurl.split(',')
      var mime = arr[0].match(/:(.*?);/)[1]
      var bstr = atob(arr[1])
      var n = bstr.length
      var u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new File([u8arr], filename, {
        type: 'png'
      })
    },

blob转base64:

blobToDataURL(blob, callback) {
    let a = new FileReader();
    a.onload = function (e) { callback(e.target.result); }
    a.readAsDataURL(blob);
}

 

posted @ 2023-09-08 08:52  larry-wang  阅读(49)  评论(0编辑  收藏  举报