簡體   English   中英

如何使用JS(Internet Explorer)以編程方式下載文件

[英]How to download a file programmatically using JS (Internet Explorer)

我有一個網頁,其中有一個按鈕,單擊該按鈕時會生成一個(通過從json進行轉換)csv文件,該文件由瀏覽器下載。 它實質上使用了jsfiddle中的邏輯。 這一切都適用於chrome,但在IE中什么也沒發生。

 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帖子,但是我沒有找到可以在頁面中使用的連貫解決方案。

jsfiddle中的代碼如何在IE中實現?

這就是我過去使用過的。 這處理IE和非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);
            }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM