我需要一个有效的(读本机)方法来转换一个ArrayBuffer到一个base64字符串,这需要在一个多部分的帖子上使用。
当前回答
这招对我很管用:
Buffer.from(myArrayBuffer).toString("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
这招对我很管用:
Buffer.from(myArrayBuffer).toString("base64");
ABtoB64(ab) {
return new Promise(res => {
const fr = new FileReader();
fr.onload = ({target: {result: s}}) => res(s.slice(s.indexOf(';base64,') + 8));
fr.readAsDataURL(new Blob([ab]));
});
}
异步方法使用文件阅读器。
下面是两个简单的函数,用于将Uint8Array转换为Base64 String
arrayToBase64String(a) {
return btoa(String.fromCharCode(...a));
}
base64StringToArray(s) {
let asciiString = atob(s);
return new Uint8Array([...asciiString].map(char => char.charCodeAt(0)));
}
function _arrayBufferToBase64( buffer ) {
var binary = '';
var bytes = new Uint8Array( buffer );
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode( bytes[ i ] );
}
return window.btoa( binary );
}
但是,非本机实现更快,例如https://gist.github.com/958841 参见http://jsperf.com/encoding-xhr-image-data/6
更新的基准测试:https://jsben.ch/wnaZC