我需要一个有效的(读本机)方法来转换一个ArrayBuffer到一个base64字符串,这需要在一个多部分的帖子上使用。


当前回答

我的建议是不要使用原生btoa策略——因为它们不能正确地编码所有ArrayBuffer的…

重写dom atob()和btoa()

由于domstring是16位编码的字符串,在大多数浏览器中调用window。如果字符超出8位ascii编码字符的范围,则Unicode字符串上的btoa将导致字符超出范围异常。

虽然我从未遇到过这种确切的错误,但我发现我尝试编码的许多ArrayBuffer都编码错误。

我会使用MDN推荐或gist。

https://github.com/beatgammit/base64-js https://gist.github.com/jonleighton/958841

其他回答

我使用TextDecode api将其转换为普通文本,然后将其转换为Base64

const uint =  new Uint8Array([ 73, 32, 108, 111, 118, 101, 32, 121, 111, 117 ]).buffer
const decoder = new TextDecoder()
const decodedText = decoder.decode(uint)
const base64Code = btoa(decodedText)

我的建议是不要使用原生btoa策略——因为它们不能正确地编码所有ArrayBuffer的…

重写dom atob()和btoa()

由于domstring是16位编码的字符串,在大多数浏览器中调用window。如果字符超出8位ascii编码字符的范围,则Unicode字符串上的btoa将导致字符超出范围异常。

虽然我从未遇到过这种确切的错误,但我发现我尝试编码的许多ArrayBuffer都编码错误。

我会使用MDN推荐或gist。

https://github.com/beatgammit/base64-js https://gist.github.com/jonleighton/958841

对于那些喜欢简短的人,这里有另一个使用数组的例子。减少不会导致堆栈溢出:

var base64 = btoa(
  new Uint8Array(arrayBuffer)
    .reduce((data, byte) => data + String.fromCharCode(byte), '')
);

在浏览器中建议的解决方案与btoa似乎很好。 但是在Node.js中btoa是不推荐使用的

建议使用buffer.toString(encoding)

like

const myString = buffer.toString("base64")

const blob = new Blob([array]);        
const reader = new FileReader();

reader.onload = (event) => {
  const dataUrl = event.target.result;
  const [_, base64] = dataUrl.split(','); 
  // do something with base64
};
   
reader.readAsDataURL(blob);

或作为一种许诺的效用:

async function encode(array) {
  return new Promise((resolve) => {
    const blob = new Blob([array]);
    const reader = new FileReader();
    
    reader.onload = (event) => {
      const dataUrl = event.target.result;
      const [_, base64] = dataUrl.split(',');
      
      resolve(base64);
    };
    
    reader.readAsDataURL(blob);
  });
}

const encoded = await encode(typedArray);