ArrayBuffer to base64 encoded string

前端 未结 12 1479
渐次进展
渐次进展 2020-11-22 07:16

I need an efficient (read native) way to convert an ArrayBuffer to a base64 string which needs to be used on a multipart post.

12条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-22 08:03

    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 );
    }
    

    but, non-native implementations are faster e.g. https://gist.github.com/958841 see http://jsperf.com/encoding-xhr-image-data/6

提交回复
热议问题