2017-01-10 30 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”。只需将其替换为您选择的文件名称和文本内容即可!