简体   繁体   English

如何使用 JavaScript 编写文档然后下载文档?

[英]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.

相关问题 如何替换 document.write? - How can i replace document.write? 如何在Javascript中动态创建文档以供下载? - How do I dynamically create a document for download in Javascript? 如何将Javascript对象写入文档。 无法对“文档”执行“写入” - How do i write Javascript object to the document. Failed to execute 'write' on 'Document' 如何使用 javascript/jquery 将数组值写入 html 文档中的不同段落? - How can I write an array values to different paragraphs in a html document using javascript/jquery? 如何将PHP代码放入JavaScript document.write - How can I put PHP code inside JavaScript document.write 如何逐行读取HTML文件并使用Javascript为每一行返回document.write()? - How can I read line by line an HTML file and return document.write() for each line with Javascript? 如何在JavaScript中回显document.write中使用的值? - How can I echo the value being used in document.write in JavaScript? 我该如何修复此Javascript以记录在多个location.href.indexOf上的写入 - how can i fix this Javascript with to document write on multiple location.href.indexOf javascript:document.write函数已重新定义,我该如何恢复它 - javascript: document.write function have redefined, how can I recover it 如何使用document.write获取div标签中javascript对象的输出? - How can i get the output of javascript object in div tag using document.write?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM