Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
213 views
in Technique[技术] by (71.8m points)

base64转blob为什么要去掉base64中的后两位

以下是网上抄的代码

function dataURLtoBlob(dataurl) {
  const arr = dataurl.split(',');
  //注意base64的最后面中括号和引号是不转译的
  const _arr = arr[1].substring(0, arr[1].length - 2);
  const mime = arr[0].match(/:(.*?);/)[1];
  const bstr = atob(_arr);
  let n = bstr.length
  const u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], {
    type: mime
  });
}

其中

//注意base64的最后面中括号和引号是不转译的
const _arr = arr[1].substring(0, arr[1].length - 2);

这两句是什么意思.
自己用的base64中, 最后两位不是括号也不是引号, 而是不确定的两位字符.
已知遇到过的情况有: "==" "I=" "CC"


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

这个不太清楚,但是我知道另一种 base64 --> blob 的方式:

const dataURL = 'data:image/gif;base64,R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs='

fetch(dataURL)
  .then(res => res.blob())
  .then(blob => {
    console.log('blob: ', blob)
  })

更多 blob --> file --> dataURL(base64) | blobURL --> blob 转换闭环可查看这里


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...