Downloading a Dynamic CSV in Internet Explorer

后端 未结 2 1238
迷失自我
迷失自我 2020-12-15 07:29

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

2条回答
  •  温柔的废话
    2020-12-15 08:07

    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.

提交回复
热议问题