blob和base64互转

2022-09-27 14:54:31 浏览数 (1)

交易场上的朋友胜过柜子里的钱款——托·富勒

blobbase64

代码语言:javascript复制
// blob转base64
async function blobToBase64(blob) {
    let buffer = await blob.arrayBuffer()
    let bytes = new Uint8Array(buffer);
    console.log(bytes)
    // do anything with the byte array here

    let binary = ''
    var len = bytes.byteLength;
    for (var i = 0; i < len; i  ) {
        binary  = String.fromCharCode(bytes[i]);
    }

    base64 = 'data:image/webp;base64,'   window.btoa(binary)
    console.log(base64)
    return base64
}

base64blob

代码语言:javascript复制
// base64转blob
      function base64ToBlob(code) {
          let parts = code.split(';base64,')
          let contentType = parts[0].split(':')[1]
          let raw = window.atob(parts[1]) // 解码base64得到二进制字符串
          let rawLength = raw.length
          let uInt8Array = new Uint8Array(rawLength) // 创建8位无符号整数值的类型化数组
          for (let i = 0; i < rawLength;   i) {
              uInt8Array[i] = raw.charCodeAt(i) // 数组接收二进制字符串
          }
          return new Blob([uInt8Array], { type: contentType })
      }

下载blob:资源路径与blobUrl互转

0 人点赞