Reputation: 29484
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?
Upvotes: 1
Views: 1233
Reputation: 3234
As mentioned, do not use atob directly for decoding Base64 encoded zip files. You can use this function mentioned in https://stackoverflow.com/a/21797381/3508516 instead.
function _base64ToArrayBuffer(base64) {
var binary_string = window.atob(base64);
var len = binary_string.length;
var bytes = new Uint8Array(len);
for (var i = 0; i < len; i++) {
bytes[i] = binary_string.charCodeAt(i);
}
return bytes.buffer;
}
Upvotes: 0
Reputation: 23798
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
.
Upvotes: 5