Skip to content

Instantly share code, notes, and snippets.

@borismus
Created June 18, 2011 02:46
Star You must be signed in to star a gist
Save borismus/1032746 to your computer and use it in GitHub Desktop.
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;
}
@hermeslm
Copy link

hermeslm commented May 4, 2018

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

@gauravr123
Copy link

@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;
}

@wenk-silvan
Copy link

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
Copy link

Thanks so much!

@navdeeshahuja
Copy link

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
Copy link

blocksan commented Mar 5, 2019

Thank you so much man. 👍

@hasmine
Copy link

hasmine commented Mar 28, 2019

Thank you so much!

@ensemblebd
Copy link

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

@efearas
Copy link

efearas commented May 3, 2019

thank you so much!

@Reegan01
Copy link

How to reverse process. Binary data to Base64?

@YOEL311
Copy link

YOEL311 commented Dec 23, 2019

How do I use it in react native?
thanks

@AhmadChaiban
Copy link

Thank you! This is great.

@KBB99
Copy link

KBB99 commented Apr 13, 2020

Thanks!

@CenkCamkiran
Copy link

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

@LemuelKL
Copy link

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
Copy link

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
Copy link

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
Copy link

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
Copy link

zenlord commented Dec 8, 2020

Thank you, @borismus!

@gorankarlic
Copy link

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
Copy link

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
Copy link

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

@gopikasireddy202
Copy link

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

@TrungJamin
Copy link

Thank you so much sir, very respects <3

@anggaputra
Copy link

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

@andreapanico10
Copy link

Thank you very much, you save my work

@mpeng
Copy link

mpeng commented Jul 20, 2021

Thank you, good work !

@marcelo-oliveira-agamenon

Thank you man! you save my day!

@jefaokpta
Copy link

Thanks buddy, save my day!

@av01d
Copy link

av01d commented Jan 20, 2022

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