Convert base64 string to ArrayBuffer

Tony picture Tony · Feb 15, 2014 · Viewed 138.2k times · Source

I need to convert a base64 encode string into an ArrayBuffer. The base64 strings are user input, they will be copy and pasted from an email, so they're not there when the page is loaded. I would like to do this in javascript without making an ajax call to the server if possible.

I found those links interesting, but they didt'n help me:

ArrayBuffer to base64 encoded string

this is about the opposite conversion, from ArrayBuffer to base64, not the other way round

http://jsperf.com/json-vs-base64/2

this looks good but i can't figure out how to use the code.

Is there an easy (maybe native) way to do the conversion? thanks

Answer

Goran.it picture Goran.it · Feb 15, 2014

Try this:

function _base64ToArrayBuffer(base64) {
    var binary_string = window.atob(base64);
    var len = binary_string.length;
    var bytes = new Uint8Array(len);
    for (var i = 0; i < len; i++) {
        bytes[i] = binary_string.charCodeAt(i);
    }
    return bytes.buffer;
}