2017-10-18 99 views
1

我有一個網頁,其中有一個按鈕,單擊它時會生成(通過從json進行轉換)csv文件,該文件由瀏覽器下載。它基本上使用了這個jsfiddle的邏輯。這一切都適用於Chrome,但在IE中,沒有任何反應。如何使用JS(Internet Explorer)以編程方式下載文件

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

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

+0

這可能有助於列出您正在測試的IE版本以及異常情況。 – Marquis

+0

對不起,實際上我以後試過的東西返回了一個運行時異常。我最初使用的代碼(類似於jsfiddle)在單擊按鈕時沒有做任何事情,但在Chrome中,文件下載並且您可以選擇打開它。這是在IE 11中。 – loremIpsum1771

回答

2

這是我過去使用過的。這處理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); 
      } 
+0

謝謝!這似乎工作。當用戶將文件保存在文件資源管理器中時,是否有一種預設文件擴展名的方法?現在它保存爲通用的「所有文件」類型。 – loremIpsum1771

+0

Nvm,我已經將「.csv」擴展名連接到一個包含文件名的變量,但是我忘記了將您使用的擴展名替換爲我的。 – loremIpsum1771

相關問題