微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

例如,如何使用JavaScript在JSON或TXT文件中编写代码。在写入文件后,如何下载它。类似于在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

谢谢。

解决方法

要保存文件,请查看FileSaver.js,它提供了一种保存文件的简单方法。写入文本文件将如下所示:

var blob = new Blob(["Hello,world!"],{type: "text/plain;charset=utf-8"});
FileSaver.saveAs(blob,"hello world.txt");

这将自动打开下载对话框。

,

您可以创建Blob。下面是一个示例,我将结果放置在此代码段的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);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。