javascriptbase64arraybuffer

How can I convert a base64 string to ArrayBuffer?


I need to convert a base64 encoding 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 an external server.

I found this question interesting, but it didn't help me: ArrayBuffer to base64 encoded string

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


Solution

  • function base64ToArrayBuffer(base64) {
        var binaryString = atob(base64);
        var bytes = new Uint8Array(binaryString.length);
        for (var i = 0; i < binaryString.length; i++) {
            bytes[i] = binaryString.charCodeAt(i);
        }
        return bytes.buffer;
    }