如何使用JS(Internet Explorer)以编程方式下载文件

lor*_*771 2 html javascript csv jquery internet-explorer

我有一个网页,其中有一个按钮,单击该按钮时会生成一个(通过从json进行转换)csv文件,该文件由浏览器下载。它实质上使用了jsfiddle中的逻辑。这一切都适用于chrome,但在IE中什么也没发生。

 var uri = 'data:text/csv;charset=utf-8,' + escape(CSV);

    // Now the little tricky part.
    // you can use either>> window.open(uri);
    // but this will not work in some browsers
    // or you will not get the correct file extension    

    //this trick will generate a temp <a /> tag
    var link = document.createElement("a");    
    link.href = uri;

    //set the visibility hidden so it will not effect on your web-layout
    link.style = "visibility:hidden";
    link.download = fileName + ".csv";

    //this part will append the anchor tag and remove it after automatic click
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
Run Code Online (Sandbox Code Playgroud)

问题似乎是Internet Explorer中不存在定位标记的下载属性。我看过许多文章和SO帖子,但是我没有找到可以在页面中使用的连贯解决方案。

jsfiddle中的代码如何在IE中实现?

Mar*_*uis 5

这就是我过去使用过的。这处理IE和非IE。

            var filename = "file.txt";
            var data = "some data";
            var blob = new Blob([data], { type: 'text/csv' });
            if (window.navigator.msSaveOrOpenBlob) {
                window.navigator.msSaveBlob(blob, filename);
            }
            else {
                var elem = window.document.createElement('a');
                elem.href = window.URL.createObjectURL(blob);
                elem.download = filename;
                document.body.appendChild(elem);
                elem.click();
                document.body.removeChild(elem);
            }
Run Code Online (Sandbox Code Playgroud)