23

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)

user1387717
  • 1,039
  • 1
  • 13
  • 30

2 Answers2

43

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.

Lee
  • 29,398
  • 28
  • 117
  • 170
Ross117
  • 1,020
  • 1
  • 12
  • 20
  • Thanks ! It is a life saver. I had a ridiculously long PDF in Base64, and it was creating error in mobile application but was working in web browser. Removing spaces did work. – Amod May 21 '15 at 11:14
  • Thank you for this. I had a similar problem but it was a trailing carriage return that was only showing up in Safari. This same methodology fixed it. – echappy Jun 03 '15 at 16:03
  • Rails apparently chops base64 pretty frequently, and Chrome will ignore the whitespace while Safari won't. Your `replace` suggestion got my app working on Safari again. Thanks for this! – Alex May 10 '16 at 04:01
  • Huge help. Couldn't figure out why my atob worked in Chrome and FF but not IE. Took way too long to find this. : ) – Cody Crumrine Oct 20 '17 at 17:34
  • Thanks, it's a life saver. – Muhammad Zubair Saleem Apr 02 '19 at 16:42
3

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);

Kent Robin
  • 2,066
  • 20
  • 19