在Internet Explorer中下载动态CSV [英] Downloading a Dynamic CSV in Internet Explorer

查看:106
本文介绍了在Internet Explorer中下载动态CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码适用于FireFox和Chrome,但不适用于IE。基本上,我有一个JSON对象,它被转换为一个数组,然后转换为csv格式,当我点击FF或Chrome中的按钮文件被下载或另存为窗口打开,但在IE中打开一个新选项卡。在一个完美的世界中IE不会存在,但在现实世界中我们必须让它工作,哈哈。

The following code works in both FireFox and Chrome, but not IE. Essentially, I have a JSON object which gets converted into an array and then to a csv format, when I click the button in FF or Chrome the file gets downloaded or the Save As window opens, but in IE a new tab opens up. In a perfect world IE would not exists, but in the real world we have to make it work, lol.

$("#csvbtn").click(function(e){
    e.preventDefault();
    var  json_obj= JSON.parse(result);
    var csv = JSON2CSV(json_obj);
    window.open("data:text/csv;charset=utf-8," + escape(csv));
});

BTW,我在Windows 8中使用IE 11来测试它,如果这有所不同。

BTW, I am using IE 11 in windows 8 to test this, if that makes a difference.

全部谢谢!

推荐答案

这是我的解决方案以防万一正在寻找解决方案。现在它适用于FF,Chrome和IE

This is my solution in case someone else is looking for a solution. now it works with FF, Chrome , and IE

var csv = JSON2CSV(json_obj);            
var blob = new Blob([csv],{type: "text/csv;charset=utf-8;"});

if (navigator.msSaveBlob) { // IE 10+
navigator.msSaveBlob(blob, "csvname.csv")
    } else {
        var link = document.createElement("a");
        if (link.download !== undefined) { // feature detection
            // Browsers that support HTML5 download attribute
            var url = URL.createObjectURL(blob);
            link.setAttribute("href", url);
            link.setAttribute("download", "csvname.csv");
            link.style = "visibility:hidden";
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }           
    }

现在我只需要弄清楚是否有保存为屏幕弹出而不是自动保存文件的方法。如果有人知道答案,请分享。现在我的用户将不得不使用这个功能。

Now I just need to figure out if there is a way to have the save as screen pop up instead of automatically saving the file. If anybody knows the answer to that please share. For now my users will have to use this functionality.

感谢所有的好答案,你们真棒。

Thanks all for all the great answers, you guys are awesome.

这篇关于在Internet Explorer中下载动态CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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