如何使用JS(Internet Explorer)以编程方式下载文件 [英] How to download a file programmatically using JS (Internet Explorer)

查看:137
本文介绍了如何使用JS(Internet Explorer)以编程方式下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个网页,其中有一个按钮,当点击它时,生成一个(通过从json转换)csv文件,由浏览器下载。它主要使用 jsfiddle 中的逻辑。这一切都适用于Chrome,但在IE中,没有任何反应。

I have a web page where there is a button that when clicked, generates a (by doing a conversion from json) csv file that is downloaded by the browser. It essentially uses the logic from this jsfiddle. This all works in chrome, but in IE, nothing happens.

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

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

The issue seems to be that the download attribute of an anchor tag doesn't exist in Internet Explorer. I've been looking at numerous articles and SO posts, but I haven't found a coherent solution that I can use in the page.

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

推荐答案

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

This is what I have used in the past. This handles IE and non-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);
            }

这篇关于如何使用JS(Internet Explorer)以编程方式下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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