web前端

js实现base64转换为Blob

2019-11-10  本文已影响0人  侬姝沁儿

新建文件bs64toBlob.js,内容如下:

export const bs64toBlob = (bs64Data, contentType, sliceSize) => {
  contentType = contentType || ''
  sliceSize = sliceSize || 512

  var byteCharacters = window.atob(bs64Data) // WindowOrWorkerGlobalScope.atob() 对用base-64编码过的字符串进行解码,基本兼容所有浏览器
  var byteArrays = []

  for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
    var slice = byteCharacters.slice(offset, offset + sliceSize)

    var byteNumbers = new Array(slice.length)
    for (var i = 0; i < slice.length; i++) {
      byteNumbers[i] = slice.charCodeAt(i)
    }

    var byteArray = new Uint8Array(byteNumbers)

    byteArrays.push(byteArray)
  }

  var blob = new Blob(byteArrays, { type: contentType })
  return blob
}
export default {
  bs64toBlob
}

使用 import ... form ...

上一篇 下一篇

猜你喜欢

热点阅读