I have an ajax call where I am calling JSReport and downloading the pdf document. In chrome and other browsers, it works correctly. The document is downloaded and I can open it. But in IE11, the document is downloaded but if I want to open the pdf file, it always shows failed to load pdf document. I debugged the code in IE11 console, but it did not give any error. Here is my code,
$.ajax({
url: 'my api url',
headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' },
type: 'POST',
data: JSON.stringify(selectedIds),
success: function (data) {
var a = document.createElement('a');
var isIE = false || !!document.documentMode;
if (!isIE) {
// This part is working properly
for (var i = 0; i < data.length; i++) {
a.href = "data:application/octet-stream;base64," + data[i];
a.target = '_blank';
a.download = 'report.pdf';
a.click();
}
} else {
// This part is for IE11 browser where I have problem to load the document after download
for (var i = 0; i < data.length; i++) {
var file = new Blob([data[i]], {
type: 'application/octet-stream'
});
window.navigator.msSaveOrOpenBlob(file, 'report.pdf');
}
}
},
fail: function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
}
});
Finally, I found the solution! I actually needed to convert base64 string data to Blob. Then we can download it. Previously, it was not converted correctly. This was why the file was downloaded but failed to load since it was damaged. Here is my code is given below,
$.ajax({
url: 'my api url',
headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' },
type: 'POST',
data: JSON.stringify(selectedIds),
success: function (data) {
var a = document.createElement('a');
var isIE = false || !!document.documentMode;
if (!isIE) {
// This part is working properly
for (var i = 0; i < data.length; i++) {
a.href = "data:application/octet-stream;base64," + data[i];
a.target = '_blank';
a.download = 'report.pdf';
a.click();
}
} else {
for (var i = 0; i < data.length; i++) {
var base64Data = data[i];
var fileName = 'report.pdf';
var byteCharacters = atob(base64Data);
var byteNumbers = new Array(byteCharacters.length);
for (var j = 0; j < byteCharacters.length; j++) {
byteNumbers[j] = byteCharacters.charCodeAt(j);
}
var byteArray = new Uint8Array(byteNumbers);
var blob = new Blob([byteArray], { type: 'application/pdf' });
window.navigator.msSaveOrOpenBlob(blob, fileName);
}
}
},
fail: function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
}
});