我想使用javascript下载文本文件。我尝试了很多场景,但没有运气。这是一个例子:
(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>
请帮忙。
答案 0 :(得分: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);
}
}
答案 1 :(得分: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");
此代码示例将显示一个对话框,用于下载名为&#34; filename.txt&#34;的文件。包含文本&#34; Hello world&#34;。只需用您选择的文件名和文本内容替换它!