Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Convert a base64 string into a binary Uint8 Array
var BASE64_MARKER = ';base64,';
function convertDataURIToBinary(dataURI) {
var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
var base64 = dataURI.substring(base64Index);
var raw = window.atob(base64);
var rawLength = raw.length;
var array = new Uint8Array(new ArrayBuffer(rawLength));
for(i = 0; i < rawLength; i++) {
array[i] = raw.charCodeAt(i);
}
return array;
}
@PAEz

This comment has been minimized.

Copy link

@PAEz PAEz commented Jul 1, 2011

Thanks, you made my day.

@borismus

This comment has been minimized.

Copy link
Owner Author

@borismus borismus commented Jul 2, 2011

Glad for it!

@Muffo

This comment has been minimized.

Copy link

@Muffo Muffo commented Oct 3, 2013

Thanks for this script!

@brettz9

This comment has been minimized.

Copy link

@brettz9 brettz9 commented Feb 5, 2014

Small nit: your "i" needs a "var" declaration to avoid it becoming global...

@sureshbora1989

This comment has been minimized.

Copy link

@sureshbora1989 sureshbora1989 commented Mar 6, 2014

Thanks Buddy :)

@fabiosantoscode

This comment has been minimized.

Copy link

@fabiosantoscode fabiosantoscode commented Jul 31, 2014

:) nice!

@sebasao

This comment has been minimized.

Copy link

@sebasao sebasao commented Aug 1, 2014

fantastic!

@ajxs

This comment has been minimized.

Copy link

@ajxs ajxs commented Jul 15, 2015

Real nice function!
Building on your example, if you're targeting Firefox and feeling adventurous you can shorten the function down to this:

var BASE64_MARKER = ';base64,';
function convertDataURIToBinaryFF(dataURI) { 
    var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length; 
    var raw = window.atob(dataURI.substring(base64Index));
    return Uint8Array.from(Array.prototype.map.call(raw,function(x) { 
            return x.charCodeAt(0); 
        })); 
};

Unfortunately Uint8Array.from() isn't supported in other browsers yet. But this example might be useful someday!

@IuryAlves

This comment has been minimized.

Copy link

@IuryAlves IuryAlves commented Jul 23, 2015

Thanks! You save my week =D

@hungconcon

This comment has been minimized.

Copy link

@hungconcon hungconcon commented Nov 17, 2015

I love you so much, same me a week, wanna invite you for a cup of coffee!

@ICEDLEE337

This comment has been minimized.

Copy link

@ICEDLEE337 ICEDLEE337 commented Nov 28, 2015

Is there any way to make this work with IE 9?

@olegrise

This comment has been minimized.

Copy link

@olegrise olegrise commented Jan 27, 2016

Nice! Worked like a charm for me. Thank you!

@Shilpa81

This comment has been minimized.

Copy link

@Shilpa81 Shilpa81 commented May 5, 2016

Hi , how to call this into jsp file , and we are using angular in our application ,,,,, can u plz help me on this

@Bachir31

This comment has been minimized.

Copy link

@Bachir31 Bachir31 commented Dec 29, 2016

Thank you! you are great !!

@noktilux

This comment has been minimized.

Copy link

@noktilux noktilux commented Sep 8, 2017

Thank you. This was very helpful.

I am using this modified version (made it a little more brief) with option to return the buffer:

function uri2array(uri, buffer) {
    var marker = ';base64,',
        raw = window.atob(uri.substring(uri.indexOf(marker) + marker.length)),
        n = raw.length,
        a = new Uint8Array(new ArrayBuffer(n));
    for(var i = 0; i < n ; i++){
        a[i] = raw.charCodeAt(i);
    }
    return buffer ? a.buffer : a;
}
@vaibhavpacharya

This comment has been minimized.

Copy link

@vaibhavpacharya vaibhavpacharya commented Oct 21, 2017

Chrome throws an error saying "dataURI.indexOf is not a function"

@mrjosshi

This comment has been minimized.

Copy link

@mrjosshi mrjosshi commented Mar 28, 2018

Cannot read property 'indexOf' of undefined

@hermeslm

This comment has been minimized.

Copy link

@hermeslm hermeslm commented May 4, 2018

I tried some others, but this works like charm!!! thanks.

@lol-to-troll

This comment has been minimized.

Copy link

@lol-to-troll lol-to-troll commented Jun 19, 2018

@borismus please declare the variable "i" in the loop. Since it's not defined it works sometimes (if i is defined elsewhere in code) and doesn't work other time.
check for bold in the below code.

Thank you so much for the code.

function convertDataURIToBinary(dataURI) {
var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
var base64 = dataURI.substring(base64Index);
var raw = window.atob(base64);
var rawLength = raw.length;
var array = new Uint8Array(new ArrayBuffer(rawLength));

for(let i = 0; i < rawLength; i++) {
array[i] = raw.charCodeAt(i);
}
return array;
}

@wenksi

This comment has been minimized.

Copy link

@wenksi wenksi commented Aug 28, 2018

Thank you so much, it's my second day working on this matter and thanks to you I finally solved it! Have a great week!

@benjaminjcash

This comment has been minimized.

Copy link

@benjaminjcash benjaminjcash commented Oct 23, 2018

Thanks so much!

@navdeeshahuja

This comment has been minimized.

Copy link

@navdeeshahuja navdeeshahuja commented Nov 20, 2018

Hey mann,
I really wanna thankyou for posting this out.
I have spent more than 5 hours scratching my head, and your 10 lines function just solved my problem.
Thankyou so much

@blocksan

This comment has been minimized.

Copy link

@blocksan blocksan commented Mar 5, 2019

Thank you so much man. 👍

@hasmine

This comment has been minimized.

Copy link

@hasmine hasmine commented Mar 28, 2019

Thank you so much!

@ensemblebd

This comment has been minimized.

Copy link

@ensemblebd ensemblebd commented Apr 25, 2019

Thank you. Saved the day on a pretty rough server post limitation (CFAccess)

@efearas

This comment has been minimized.

Copy link

@efearas efearas commented May 3, 2019

thank you so much!

@Reegan01

This comment has been minimized.

Copy link

@Reegan01 Reegan01 commented Dec 20, 2019

How to reverse process. Binary data to Base64?

@YOEL311

This comment has been minimized.

Copy link

@YOEL311 YOEL311 commented Dec 23, 2019

How do I use it in react native?
thanks

@AhmadChaiban

This comment has been minimized.

Copy link

@AhmadChaiban AhmadChaiban commented Jan 6, 2020

Thank you! This is great.

@KBB99

This comment has been minimized.

Copy link

@KBB99 KBB99 commented Apr 13, 2020

Thanks!

@CenkCamkiran

This comment has been minimized.

Copy link

@CenkCamkiran CenkCamkiran commented Apr 30, 2020

I got the error. Error is : window is not defined. Any ideas?

@LemuelKL

This comment has been minimized.

Copy link

@LemuelKL LemuelKL commented Jul 5, 2020

I got the error. Error is : window is not defined. Any ideas?

That way you are not running this code in a browser, but on a NodeJs backend?
You can try using this package's atob() instead of window.atob()https://www.npmjs.com/package/atob

@CenkCamkiran

This comment has been minimized.

Copy link

@CenkCamkiran CenkCamkiran commented Jul 7, 2020

I got the error. Error is : window is not defined. Any ideas?

That way you are not running this code in a browser, but on a NodeJs backend?
You can try using this package's atob() instead of window.atob()https://www.npmjs.com/package/atob

Woaah! Thank you very much! It worked.

@CristianCuartas

This comment has been minimized.

Copy link

@CristianCuartas CristianCuartas commented Aug 25, 2020

Hola, espero se encuentren bien.
¿Alguien pudiera ayudarme con la implementación en React JS?

Según entiendo:
1.) Convierten el archivo a base 64.
2.) Utilizan la función convertDataURIToBinary pasando como parámetro el base 64 retornando un arreglo
3.) El arreglo de retorno lo pasan como parámetro a PDFJS.getDocument(array)

Mi pregunta es, ¿donde llaman a PDFJS.getDocument(array) para que muestre el pdf en la librería?
Sólo estoy un poco perdido en la implementación si alguien pudiera aclararme un poco lo agradecería, gracias.

@CristianCuartas

This comment has been minimized.

Copy link

@CristianCuartas CristianCuartas commented Aug 25, 2020

Hello, I hope you are well.
Could someone help me with the implementation in React JS?

As I understand it:
1.) They convert the file to base 64.
2.) They use the function convertDataURIToBinary passing as parameter the base 64 returning an array
3.) The return array is passed as a parameter to PDFJS.getDocument(array)

My question is, where do you call PDFJS.getDocument(array) to display the pdf in the library?
I'm just a little lost in the implementation if someone could clarify it for me a little bit I would appreciate it, thanks.

@zenlord

This comment has been minimized.

Copy link

@zenlord zenlord commented Dec 8, 2020

Thank you, @borismus!

@gorankarlic

This comment has been minimized.

Copy link

@gorankarlic gorankarlic commented Dec 10, 2020

One liner to convert Base64 to Uint8Array:

function Uint8ArrayFromBase64(base64)
{
    return Uint8Array.from(window.atob(base64), (v) => v.charCodeAt(0));
}

One liner to convert Base64Url to Uint8Array:

function Uint8ArrayFromBase64Url(base64Url)
{
    return Uint8Array.from(window.atob(base64Url.replace(/-/g, "+").replace(/_/g, "/")), (v) => v.charCodeAt(0));
}
@jiunyuchen

This comment has been minimized.

Copy link

@jiunyuchen jiunyuchen commented Dec 17, 2020

ERROR: Uncaught DOMException: Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded
I am running it with typescript react. Any idea?

@crhenrici

This comment has been minimized.

Copy link

@crhenrici crhenrici commented Apr 14, 2021

Thanks for this! The only solution that worked for me @borismus

@gopikasireddy202

This comment has been minimized.

Copy link

@gopikasireddy202 gopikasireddy202 commented May 21, 2021

How to convert this recordfile:///var/mobile/Containers/Data/Application/9C0F0870-EA7F-4CD2-9C42-30A3E9862012/Library/Caches/hello.m4a into binary format.

@TrungJamin

This comment has been minimized.

Copy link

@TrungJamin TrungJamin commented May 30, 2021

Thank you so much sir, very respects <3

@anggaputra

This comment has been minimized.

Copy link

@anggaputra anggaputra commented Jun 14, 2021

Thank you very much for this, after a week of pulling my hair out. This is the only solution that works for me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment