繁体   English   中英

如何使用 JS 从 HTML 文本区域下载文本作为 .txt 文件?

[英]How can I download text from an HTML text area as a .txt file using JS?

我正在开发一个项目,该项目随机生成一组用于密码的字符,并希望用户能够将结果下载为文本文件。 我已经阅读了一些关于 BLOB 的内容以及其他一些无效的方法。 如果有人可以提供一种有效的方法,那将是一个很大的帮助。

TL;DR:需要一种方法来使用 JS 从 HTML textarea 下载文本作为 a.txt 文件

您应该能够以编程方式创建一个链接,该链接使用数据 url和您的文本,添加download属性以便浏览器下载而不是导航(并指定文件名),然后单击它。

这不会作为 SO 片段运行,可能是出于安全原因,但它应该可以在世界范围内运行(您可以在开发工具控制台中复制/粘贴它来测试它):

 const generatedText = 'some generated blob of text'; // create an anchor element that we can programmatically click const a = document.createElement('a'); // set up a data uri with the text a.href = `data:text/plain,${generatedText}`; // set the download attribute so it downloads and uses this as a filename a.download = 'the-name-of-the-file.txt'; // stick it in the document document.body.appendChild(a); // click it a.click();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM