IE 9+下载属性解决方法 [英] IE 9+ Download Attribute workaround

查看:101
本文介绍了IE 9+下载属性解决方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从我的网络服务下载文件。我需要将复杂的元数据传递给服务器以了解如何下载文件。以下是我能够在常绿浏览器中实现这一目标的方法:

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

当然感觉IE上没有下载属性我无法发布。我之前使用过的解决方法是:

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

然后在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.

你如何解决这个问题?

推荐答案

如果你只关心最近的浏览器,你可以看一下使用 FileSaver.js 。在IE10 +上运行时,它使用 navigator.msSaveOrOpenBlob

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

这篇关于IE 9+下载属性解决方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆