Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
29
rated 0 times [  33] [ 4]  / answers: 1 / hits: 171034  / 9 Years ago, wed, january 27, 2016, 12:00:00

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?


More From » post

 Answers
8

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

[#63542] Monday, January 25, 2016, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
myrap

Total Points: 407
Total Questions: 105
Total Answers: 109

Location: Cambodia
Member since Thu, Oct 7, 2021
3 Years ago
myrap questions
Tue, Feb 8, 22, 00:00, 2 Years ago
Wed, Jan 15, 20, 00:00, 4 Years ago
Thu, Oct 24, 19, 00:00, 5 Years ago
Thu, Oct 3, 19, 00:00, 5 Years ago
Mon, Aug 12, 19, 00:00, 5 Years ago
;