简体   繁体   中英

How can I make my file download work on IE and safari?

I'm trying to create and download a file on client side with the following code:

function downloadFile(filename, text) {
    var pom = document.createElement('a');
    pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
    pom.setAttribute('download', filename);
    pom.click();
}

Although this only works on chrome. Nothing happens on safari and IE. How can I make it work?

Not sure if youve figured this out or not but for this to work in safari you need to create an event and dispatch on the created element like this:

    var downloadLink = document.createElement('a');
    downloadLink.setAttribute('href', 'data:application/octet;charset=utf-8,' + encodeURIComponent(data));
    downloadLink.setAttribute('download', fileName);
    downloadLink.style.display = "none";
    downloadLink.onclick = function (event) {
        document.body.removeChild(event.target);
    };

    var clk = document.createEvent("MouseEvent");
    clk.initEvent("click", true, true);
    downloadLink.dispatchEvent(clk);

    document.body.appendChild(downloadLink);
    downloadLink.dispatchEvent(clk);`

I used this to save my file in CSV/excel format and works in chrome/IE/Safari
refer and make changes needed

        var fileName = name + "["+ name1 +"]";
        var uri = 'data:text/csv;charset=utf-8,' + escape(finalResult);
        var link = document.createElement("a");    
        link.href = uri;
        link.style = "visibility:hidden";
        link.download = fileName + ".csv";
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        location.reload();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM