[英]How can I write in a document with JavaScript and then download the document?
How can I write for example in a JSON or TXT file with JavaScript.例如,我如何使用 JavaScript 在 JSON 或 TXT 文件中编写代码。 After I write in the file how can I download it.
在我写入文件后,我该如何下载它。 Similar to doing this in python
类似于在 python 中执行此操作
File = open("FileToWriteIn.txt", "wb")
File.write("Hello")
File.close()
# Then I want to download the file which in this case would be FileToWriteIn.txt but I want to
# do this with JavaScript
Thanks.谢谢。
For file saving take a look at FileSaver.js which provides a simple approach to save files.对于文件保存,请查看FileSaver.js ,它提供了一种简单的文件保存方法。 Writing to a text file will then look like this:
写入文本文件将如下所示:
var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
FileSaver.saveAs(blob, "hello world.txt");
This will automatically open the download dialogue.这将自动打开下载对话框。
You can create Blobs,.您可以创建 Blob,。 Below is an example, I've placed the result inside an iFrame for this snippet, but you could use window.open instead if you wanted to download.
下面是一个示例,我已将结果放置在此代码段的 iFrame 中,但如果您想下载,则可以改用 window.open。
//create blob const blob = new Blob([JSON.stringify( { hello: 'world' })], {type : 'application/json'}); //turn into a URL for download or view etc. const url = URL.createObjectURL(blob); //for testing, lets put in an iframe const frame = document.createElement('iframe'); frame.setAttribute('src',url); document.body.appendChild(frame);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.