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


当前回答

使用uint8-to-b64包在浏览器和Node.js中进行编码/解码

其他回答

你可以使用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

}

这个方法更快,因为没有字符串连接在其中运行。

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

如果你可以添加一个库,base64-arraybuffer:

yarn add base64-arraybuffer

然后:

encode(buffer) -将ArrayBuffer编码为base64字符串 decode(str) -解码base64字符串到ArrayBuffer

我使用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)

这招对我很管用:

Buffer.from(myArrayBuffer).toString("base64");