Muhammad Kholid B
Muhammad Kholid B

Reputation: 477

Javascript return file from web service

I am trying to make a file download using javascript from a web service. The web service return data in JSON string with format below:

{
    "status": "OK",
    "encodedFile": "AAAAX3JlbHMvLnJlbHOtksFOwzAMhu99iij31d2QEEJNd0FIu01oPEBI3DZqE0eJB+XtiZAQDDHYgWOS358/W2m3i5/FM6bsKCi5rhspMBiyLgxKPh7uVzdy21VV+4Cz5pLJo4tZlKKQlRyZ4y1ANiN6nWuKGMpLAAAAX3JlbHMvLnJlbHOtksFOwzAMhu99iij31d2QEEJNd0FIu01oPEBI3DZqE0eJB+XtiZAQDDHYgWOS358/W2m3i5/FM6bsKCi5rhspMBiyLgxKPh7uVzdy21VV+4Cz5pLJo4tZlKKQlRyZ4y1ANiN6nWuKGMpL"
}

The encodedFile is a Base64 encoded form of file bytes from the web service. The web service get the file in the server, convert the file to be array of bytes, and then encode the array of bytes to string using Base64, and return the response in JSON format, so the javascript get the string. After I get the the string and decode it (I get the bytes of file), how I can return it (the bytes) as a file download? Basically, now I have the bytes of file, and I want to return it to be a file download.

I am using jquery ajax to get the response, get the "status", and get the "encodedFile". Any help or suggestion will be appreciated. Thank you in advance.

Upvotes: 3

Views: 2427

Answers (1)

Aaron Hammond
Aaron Hammond

Reputation: 617

First, we can take the Base64 encoded blob and decode it. Then we take the resultant string, coerce it into a unsigned 8-bit byte array (as it should be), and create a blob from the bytes. Finally, we create a URL for this blob, and set the window.location to it (although you'd probably want to open the blob in a separate tab instead).

var data = atob("AAAAX3JlbHMvLnJlbHOtksFOwzAMhu99iij31d2QEEJNd0FIu01oPEBI3DZqE0eJB+XtiZAQDDHYgWOS358/W2m3i5/FM6bsKCi5rhspMBiyLgxKPh7uVzdy21VV+4Cz5pLJo4tZlKKQlRyZ4y1ANiN6nWuKGMpLAAAAX3JlbHMvLnJlbHOtksFOwzAMhu99iij31d2QEEJNd0FIu01oPEBI3DZqE0eJB+XtiZAQDDHYgWOS358/W2m3i5/FM6bsKCi5rhspMBiyLgxKPh7uVzdy21VV+4Cz5pLJo4tZlKKQlRyZ4y1ANiN6nWuKGMpL")
var bytes = new Array(data.length);
for (var i = 0; i < data.length; i++) {
    bytes[i] = data.charCodeAt(i);
}
bytes = new Uint8Array(bytes);
var blob = new Blob([bytes]);
window.location = URL.createObjectURL(blob);

Upvotes: 3

Related Questions