IE 9+ Download Attribute workaround

2019-07-07 05:36发布

问题:

I am trying to download a file from my web service. I need to pass complex meta data to the server to know how to download the file. Here is how Im able to accomplish that 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();
});

of course sense the download attribute is not available on IE I'm not able to post. A workaround I've used before is:

$("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>

problem is I can't pass a object like that. Sure I can put a hidden input and serialize its value but my object is kinda big so that ends up being a problem.

How do you work around this?

回答1:

If you're only concerned about recent browsers you might take a look at using 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();