0
votes

I am receiving the content of a zip file (from an API) as a Base64-encoded string.

If I paste that string into Notepad++ and go

Plugins > MIME Tools > Base64 Decode

and save it as test.zip, it becomes a valid zip file, I can open it.

Now, I am trying to achieve the same thing in JavaScript.

I have tried atob(), and probably everything mentioned in the answers here and the code from Mozilla doc.

atob produces a similar content, but some characters are decoded differently (hence becomes an invalid zip file). The other methods throw an invalid URI error.

How can I reproduce Notepad++ behaviour in JavaScript?

1
How are you turning the output from atob() into a file? - Phil
@Phil This is what I used to save the file: stackoverflow.com/questions/13405129/… - Aximili

1 Answers

2
votes

The window.atob is only good for decoding data which fits in a UTF-8 string. Anything which cannot be represented in UTF-8 string will not be equal to its binary form when decoded. Javascript, at most, will try encoding the resultant bytes in to UTF-8 character sequence. This is the reason why your zip archive is rendered invalid eventually.

The moment you do the following:

var data = window.atob(encoded_data)

... you are having a different representation of your data in a UTF-8 string which is referenced by the variable data.

You should decode your binary data directly to an ArrayBuffer. And window.atob is not a good fit for this.

Here is a function which can convert base64 encoded data directly in to an ArrayBuffer.