我需要一个有效的(读本机)方法来转换一个ArrayBuffer到一个base64字符串,这需要在一个多部分的帖子上使用。
当前回答
这对我来说很有效:
var base64String = btoa(String.fromCharCode.apply(null, new Uint8Array(arrayBuffer)));
在ES6中,语法稍微简单一些:
const base64String = btoa(String.fromCharCode(...new Uint8Array(arrayBuffer)));
正如评论中指出的,当ArrayBuffer较大时,此方法可能会在某些浏览器中导致运行时错误。确切的大小限制在任何情况下都取决于实现。
其他回答
你可以使用array .prototype.slice从ArrayBuffer中派生一个普通数组。 使用像Array.prototype.map这样的函数将字节转换为字符并将它们连接在一起形成字符串。
function arrayBufferToBase64(ab){
var dView = new Uint8Array(ab); //Get a byte view
var arr = Array.prototype.slice.call(dView); //Create a normal array
var arr1 = arr.map(function(item){
return String.fromCharCode(item); //Convert
});
return window.btoa(arr1.join('')); //Form a string
}
这个方法更快,因为没有字符串连接在其中运行。
我的建议是不要使用原生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
还有另一种异步方式使用Blob和FileReader。
我没有测试性能。但这是一种不同的思维方式。
function arrayBufferToBase64( buffer, callback ) {
var blob = new Blob([buffer],{type:'application/octet-binary'});
var reader = new FileReader();
reader.onload = function(evt){
var dataurl = evt.target.result;
callback(dataurl.substr(dataurl.indexOf(',')+1));
};
reader.readAsDataURL(blob);
}
//example:
var buf = new Uint8Array([11,22,33]);
arrayBufferToBase64(buf, console.log.bind(console)); //"CxYh"
OP没有指定运行环境,但如果你使用Node.JS,有一个非常简单的方法来做这件事。
与官方Node.JS文档一致 https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings
// This step is only necessary if you don't already have a Buffer Object
const buffer = Buffer.from(yourArrayBuffer);
const base64String = buffer.toString('base64');
另外,如果你在Angular下运行,缓冲区类也会在浏览器环境中可用。
如果你可以添加一个库,base64-arraybuffer:
yarn add base64-arraybuffer
然后:
encode(buffer) -将ArrayBuffer编码为base64字符串 decode(str) -解码base64字符串到ArrayBuffer