ArrayBuffer to base64 encoded 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 );}
but, non-native implementations are faster e.g. https://gist.github.com/958841see http://jsperf.com/encoding-xhr-image-data/6
This works fine for me:
var base64String = btoa(String.fromCharCode.apply(null, new Uint8Array(arrayBuffer)));
In ES6, the syntax is a little simpler:
const base64String = btoa(String.fromCharCode(...new Uint8Array(arrayBuffer)));
As pointed out in the comments, this method may result in a runtime error in some browsers when the ArrayBuffer
is large. The exact size limit is implementation dependent in any case.
For those who like it short, here's an other one using Array.reduce
which will not cause stack overflow:
var base64 = btoa( new Uint8Array(arrayBuffer) .reduce((data, byte) => data + String.fromCharCode(byte), ''));