IE 9+ Download workaround
I am trying to download a file from a web service. I need to pass complex metadata to the server to find out how to upload a file. This is how I can achieve this in evergreen browsers:
// i use angular but not important for this demo
$http.post({ /* complex object */ }).then(xhr){
// use download attribute
// http://davidwalsh.name/download-attribute
var hiddenElement = document.createElement('a');
hiddenElement.href = 'data:attachment/csv,' + encodeURI(xhr.data);
hiddenElement.target = '_blank';
hiddenElement.download = $scope.filename + '.csv';
hiddenElement.click();
hiddenElement.remove();
});
The download attribute is of course not available in IE, which I can't post. The workaround I used before:
$("body>#download_iFrame").remove();
$("body").append('<iframe name="downloadFrame" id="download_iFrame" style="display:none;" src="" />');
$("#form-download")[0].submit();
and then in html
<form target="downloadFrame"
action="'api/search/export/'"
id="form-download"></form>
The problem is that I cannot pass such an object. Of course I can put hidden input and serialize its value, but my object is very large, so the problem becomes a problem.
How do you get around this?
+3
source to share
1 answer
If you're only concerned about a recent browser, you might want to take a look at FileSaver.js . When running on IE10 +, it uses navigator.msSaveOrOpenBlob .
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = "blob";
xhr.onload = fuction (eventInfo) {
if (this.status == 200) {
var blob = this.response;
// FileSaver.js usage:
saveAs(blob, "filename.ext");
// Or IE10+ specific:
navigator.msSaveOrOpenBlob(blob, "filename.ext");
}
};
xhr.send();
0
source to share