Reputation: 33
Via Web API, download a blob file formatted as CSV to open in Excel. Code below works in Chrome and Firefox but not IE or Edge. Except, when I add the line "window.open(url)" which is shown below, it then opens in Edge but still not IE (but with this extra line Chrome then opens another tab that isn't necessary and doesn't even work but the file still downloads and opens). Hoping for answers on how to get this to work correctly in each of these browsers. Also get an 'Access is denied' message in IE and Edge but this message doesn't stop the file from downloading and opening via Edge with the extra line I mentioned.
var fileName = 'MovieList.csv';
var a = document.createElement("a");
a.style = "display: none";
var blob = new Blob([data], { type: "octet/stream" });
var url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
document.body.appendChild(a);
a.click();
window.open(url);
window.URL.revokeObjectURL(url);
Upvotes: 0
Views: 2402
Reputation: 1310
IE is always fun! I had run into this issue previously so I looked back to see what I'd done. Here's the snippet I have:
var blob = new Blob([csvFile], { type: 'text/csv;charset=utf-8;' });
if (navigator.msSaveBlob) { // IE 10+
navigator.msSaveBlob(blob, filename);
} else {
var link = document.createElement("a");
if (link.download !== undefined) { // feature detection
// Browsers that support HTML5 download attribute
var url = URL.createObjectURL(blob);
link.setAttribute("href", url);
link.setAttribute("download", filename);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
It looks for the IE 10+ function 'navigator.msSaveBlob' and if found, uses that to save the blob. Otherwise, it uses similar logic to what you posted for any other browser.
Upvotes: 1