2

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

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.

How can the code from the jsfiddle be implemented in IE?

loremIpsum1771
  • 2,497
  • 5
  • 40
  • 87
  • It may help to list what version of IE you're testing and what the exception is. – Marquis Oct 18 '17 at 20:40
  • Sorry, actually something I was trying later returned a runtime exception. The code I initially used (which is similar to the jsfiddle) just did nothing when the button was clicked, but in chrome, the file downloads and you have the option to open it. This is in IE 11. – loremIpsum1771 Oct 18 '17 at 20:51

1 Answers1

7

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);
            }
Marquis
  • 531
  • 1
  • 4
  • 13
  • Thanks! This seems to work. Is there a way to have a preset file extension when the user saves the file in file explorer? Right now it's saving as the generic "all files" type. – loremIpsum1771 Oct 18 '17 at 21:20
  • Nvm, I had already concatenated the ".csv" extension to a variable containing the filename but I forgot to switch out the one you used with mine. – loremIpsum1771 Oct 19 '17 at 14:13