Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DOM Exception 5 INVALID CHARACTER error on valid base64 image string in javascript

I'm trying to decode a base64 string for an image back into binary so it can be downloaded and displayed locally by an OS.

The string I have successfully renders when put as the src of an HTML IMG element with the data URI preface (data: img/png;base64, ) but when using the atob function or a goog closure function it fails.

However decoding succeeds when put in here: http://www.base64decode.org/

Any ideas?

EDIT: I successfully got it to decode with another library other than the built-in JS function. But, it still won't open locally - on a Mac says it's damaged or in an unknown format and can't get opened.

The code is just something like:

imgEl.src = 'data:img/png;base64,' + contentStr; //this displays successfully
decodedStr = window.atob(contentStr); //this throws the invalid char exception but i just
//used a different script to get it decode successfully but still won't display locally

the base64 string itself is too long to display here (limit is 30,000 characters)

like image 925
user1387717 Avatar asked Feb 04 '13 21:02

user1387717


People also ask

How do you check whether the string is base64 encoded or not in JavaScript?

To determine if a string is a base64 string using JavaScript, we can check if a base64 string against a regex. For instance, we can write: const base64regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?

What characters are invalid in base64?

The base 64 digits in ascending order from zero are the uppercase characters 'A' to 'Z', lowercase characters 'a' to 'z', numerals '0' to '9', and the symbols '+' and '/'. % is not allowed in base64 encoding.

How do I know if a string is base64?

In base64 encoding, the character set is [A-Z, a-z, 0-9, and + /] . If the rest length is less than 4, the string is padded with '=' characters. ^([A-Za-z0-9+/]{4})* means the string starts with 0 or more base64 groups.


2 Answers

I was just banging my head against the wall on this one for awhile.

There are a couple of possible causes to the problem. 1) Utf-8 problems. There's a good write up + a solution for that here.

In my case, I also had to make sure all the whitespace was out of the string before passing it to atob. e.g.

function decodeFromBase64(input) {   input = input.replace(/\s/g, '');   return atob(input); } 

What was really frustrating was that the base64 parsed correctly using the base64 library in python, but not in JS.

like image 160
Ross117 Avatar answered Sep 17 '22 13:09

Ross117


I had to remove the data:audio/wav;base64, in front of the b64, as this was given as part of the b64.

var data = b64Data.substring(b64Data.indexOf(',')+1);

var processed = atob(data);

like image 38
Kent Robin Avatar answered Sep 20 '22 13:09

Kent Robin