ArrayBuffer to base64 encoded string

zaheer picture zaheer · Feb 13, 2012 · Viewed 216.3k times · Source

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

Answer

mobz picture mobz · Feb 27, 2012
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