【问题标题】:Prompt user to download output as txt file提示用户将输出下载为 txt 文件
【发布时间】:2016-10-23 00:51:29
【问题描述】:

我正在寻找带有脚本的帮助,该脚本允许用户通过单击我的“导出”按钮从文本区域下载输出(通过提示他们保存)。

<textarea id="output" class="form-control text-box noresize" rows="4" placeholder="OUTPUT">
</textarea>

我得到的最接近的答案是下面这个,但显然它是在创建一个文件,而不是使用我的输出:

var a = window.document.createElement('a');
a.href = window.URL.createObjectURL(new Blob(['Test,Text'], {type: 'text/csv'}));
a.download = 'test.csv';

// Append anchor to body.
document.body.appendChild(a)
a.click();

// Remove anchor from body
document.body.removeChild(a)

我们将非常感谢提供任何帮助。

【问题讨论】:

标签: javascript


【解决方案1】:

使用您的方法,只需将 textarea 的值传递给 createObjectURL 函数。

<textarea id="output" class="form-control text-box noresize" rows="4" placeholder="This text will be downloaded as a file.">
</textarea>

<br>
<button id="download">Download</button>

<script>
document.getElementById('download').addEventListener("click", download);

function download(){
    var text = document.getElementById('output');
    var a = window.document.createElement('a');
    a.href = window.URL.createObjectURL(new Blob([text.value], {type: 'text/plain'}));
    a.download = 'test.txt';

    document.body.appendChild(a)
    a.click();
    document.body.removeChild(a)
}
</script>

【讨论】:

【解决方案2】:

试试这个:

var txt  = document.getElementById('content').value;

document.getElementById('link').onclick = function(){
    this.href = 'data:text/plain;charset=utf-8,' + encodeURIComponent(txt);
};

document.getElementById('content').onchange = function(){
    txt = document.getElementById('content').value;
};
<body>

    <div>
	<textarea id="content">Hello World</textarea>
    </div>

    <a href="" id="link" download="content.txt">Download</a>
  
</body>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-08
    • 2016-07-16
    • 2010-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-07
    相关资源
    最近更新 更多