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
jsPerf.com is jsPerf.app now: https://jsperf.app/encoding-xhr-image-data/51
Updated benchmarks: https://jsben.ch/wnaZC
Answer from mobz on Stack Overflowfunction _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
jsPerf.com is jsPerf.app now: https://jsperf.app/encoding-xhr-image-data/51
Updated benchmarks: https://jsben.ch/wnaZC
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.
Convert ArrayBuffer to Base64
Base64 encode ArrayBuffer
How do I convert an ArrayBuffer to base64url and vice versa?
Canonical way to convert image arraybuffer to base64?
Anyone has experience converting an arraybuffer response to base64 in react native before?
Need to find other methods as btoa & atob are deprecated.
» npm install base64-arraybuffer
I want to convert
[146, 158, 30, 105, 37, 64, 188, 176, 151, 69, 135, 48, 116, 103, 158, 180, 180, 93, 233, 205, 246, 73, 21, 84, 115, 104, 123, 243, 69, 20, 98, 208]
into
kp4eaSVAvLCXRYcwdGeetLRd6c32SRVUc2h780UUYtA
and vice versa.
I know I can convert the ArrayBuffer into a base64url string because this is a value from a toJSON() function from Web Authentication: An API for accessing Public Key Credentials - Level 3. But I don't know how to convert it back.