[英]How to create .txt file using JavaScript / HTML5?
我是javascript的新手。 互聯網上與使用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);
})();
和HTML:
<textarea id="textbox">Type something here</textarea> <button id="create">Create file</button>
<a download="info.txt" id="downloadlink" style="display: none">Download</a>
取自這個小提琴:
一個非常快速和簡單的解決方案是使用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, "hello world.txt");
此代碼示例將顯示一個對話框,用於下載名為“hello world.txt”的文件,其中包含文本“Hello,world!”。 只需用您選擇的文件名和文本內容替換它!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.