Download File from Bytes in JavaScript

JavascriptPostRequestResponse

Javascript Problem Overview


I want to download the file which is coming in the form of bytes from the AJAX response.

I tried to do it this way with the help of Blob:

var blob=new Blob([resultByte], {type: "application/pdf"});
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download="myFileName.pdf";
link.click();

It is in fact downloading the pdf file but the file itself is corrupted.

How can I accomplish this?

Javascript Solutions


Solution 1 - Javascript

I asked the question long time ago, so I might be wrong in some details.

It turns out that Blob needs array buffers. That's why base64 bytes need to be converted to array buffers first.

Here is the function to do that:

function base64ToArrayBuffer(base64) {
    var binaryString = window.atob(base64);
    var binaryLen = binaryString.length;
    var bytes = new Uint8Array(binaryLen);
    for (var i = 0; i < binaryLen; i++) {
       var ascii = binaryString.charCodeAt(i);
       bytes[i] = ascii;
    }
    return bytes;
 }

Here is my function to save a pdf file:

function saveByteArray(reportName, byte) {
    var blob = new Blob([byte], {type: "application/pdf"});
    var link = document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    var fileName = reportName;
    link.download = fileName;
    link.click();
};

Here is how to use these two functions together:

var sampleArr = base64ToArrayBuffer(data);
saveByteArray("Sample Report", sampleArr);

Solution 2 - Javascript

You just need to add one extra line and it should work. Your response is byte array from your server application

var bytes = new Uint8Array(resultByte); // pass your byte response to this constructor

var blob=new Blob([bytes], {type: "application/pdf"});// change resultByte to bytes

var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download="myFileName.pdf";
link.click();

Solution 3 - Javascript

Set Blob type at Blob constructor instead of at createObjectURL

var blob = new Blob([resultByte], {type: "application/pdf"});
var link = document.createElement("a");
link.href = window.URL.createObjectURL(blob);
link.download = "myFileName.pdf";
link.click();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJahongir RahmonovView Question on Stackoverflow
Solution 1 - JavascriptJahongir RahmonovView Answer on Stackoverflow
Solution 2 - JavascriptKrishnaSinghView Answer on Stackoverflow
Solution 3 - Javascriptguest271314View Answer on Stackoverflow