2017-01-10 41 views
0

我想使用javascript下載文本文件。我嘗試過很多場景,但都沒有運氣。這裏有一個例子:下載txt文件「encodeURIComponent」在IE中不工作

(function() { 
 
    var textFile = null, 
 
    makeTextFile = function(text) { 
 
     var data = new Blob([text], { 
 
     type: 'text/plain' 
 
     }); 
 

 
     // If we are replacing a previously generated file we need to 
 
     // manually revoke the object URL to avoid memory leaks. 
 
     if (textFile !== null) { 
 
     window.URL.revokeObjectURL(textFile); 
 
     } 
 

 
     textFile = window.URL.createObjectURL(data); 
 

 
     return textFile; 
 
    }; 
 

 

 
    var create = document.getElementById('create'), 
 
    textbox = document.getElementById('textbox'); 
 

 
    create.addEventListener('click', function() { 
 
    var link = document.getElementById('downloadlink'); 
 
    link.href = makeTextFile(textbox.value); 
 
    link.style.display = 'block'; 
 
    }, false); 
 
})();
<textarea id="textbox">Type something here</textarea> 
 
<button id="create">Create file</button> 
 
<a download="info.txt" id="downloadlink" style="display: none">Download</a>

請幫助。

+2

請不要使用這樣的技巧來規避「問題中的代碼」政策。如果jsFiddle失敗,你的問題將無法回答。請編輯它以包含所有相關的代碼。 –

+0

另外,具體哪個版本的IE? Blob'在

+2

@ JituJoshi中不受支持按照第一條評論與Rory約定。這一次,我已經爲你做了,但做法是在問題本身添加相關的代碼。 – Jai

回答

0

謝謝大家的回覆。我找到了解決方案。

function download(data, filename, type) { 
    var a = document.createElement("a"), 
     file = new Blob([data], { type: type }); 
    if (window.navigator.msSaveOrOpenBlob) // IE10+ 
     window.navigator.msSaveOrOpenBlob(file, filename); 
    else { // Others 
     var url = URL.createObjectURL(file); 
     a.href = url; 
     a.download = filename; 
     document.body.appendChild(a); 
     a.click(); 
     setTimeout(function() { 
      document.body.removeChild(a); 
      window.URL.revokeObjectURL(url); 
     }, 0); 
    } 
} 
0

一個非常快速和簡單的解決方案是使用FileSaver.js: https://raw.githubusercontent.com/eligrey/FileSaver.js/master/FileSaver.js

然後只需要2行代碼來下載一個txt文件:

var blob = new Blob(["Hello World"], {type: "text/plain;charset=utf-8"}); 

saveAs(blob, "filename.txt"); 

此代碼示例將顯示一個對話框,以下載名爲「filename.txt」的文件,其中包含文本「Hello world」。只需將其替換爲您選擇的文件名稱和文本內容即可!