如何从文本区域的值中保存 .txt 文件?

How can I save a .txt file from the value of a textarea?

我希望能够在 textarea 中写入一些文本,然后单击按钮让浏览器下载包含我在 textarea 中写入的文本的 .txt 文件。

我不知道该怎么做。我应该尝试什么? 有什么方法可以让我在不使用数据库或服务器的情况下将它下载给我吗?

从文本区域获取数据:

var textcontent = document.getElementById("textareaID").value;

要下载为 txt 文件:

var downloadableLink = document.createElement('a');
downloadableLink.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(textcontent));
downloadableLink.download = "myFile" + ".txt";
document.body.appendChild(downloadableLink);
downloadableLink.click();
document.body.removeChild(downloadableLink);

您可以创建一个包含 <textarea> 的输入字段。

示例: HTML

<h2>Create .txt file</h2>
<div>
   <label for="fname">File name (without .txt):</label>
   <br>
   <input type="text" id="fname" name="fname"><br><br>
   <label for="fcontent">File Content:</label>
   <br>
   <textarea id="fcontent" name="w3review" rows="4" cols="50"></textarea>
   <br>
   <button id="create">Create File</button>
   <a download="info.txt" id="downloadlink" style="display: none">Download Here</a>
</div>

Javascript:

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

            if (textFile !== null) {
                window.URL.revokeObjectURL(textFile);
            }

            textFile = window.URL.createObjectURL(data);

            return textFile;
        };


    var create = document.getElementById('create');
    var fileContent = document.getElementById("fcontent");

    create.addEventListener('click', function() {
        const fileName = document.getElementById("fname").value;
        document.getElementById("downloadlink").setAttribute("download", fileName);
        var link = document.getElementById('downloadlink');
        link.href = makeTextFile(fileContent.value);
        link.style.display = 'block';
    }, false);
})();

您可以看到现场演示here

注意:如果您想将 HTML 文件设为默认文件而不是 .txt 文件,您可以通过将 JavaScript 文件中的 type: 'text/plain' 更改为type: 'text/html'

参见 JSFiddler

上的工作示例

Javascript/JQuery

$('#mybutton').click(function(){
     var data = $('#mytextarea').val();
     this.href = "data:text/plain;charset=UTF-8,"  + encodeURIComponent(data);
});

HTML

<textarea id="mytextarea"></textarea>
<a id="mybutton" href="" download="output.txt">Export to .txt</a>