【问题标题】:How can I write in a document with JavaScript and then download the document?如何使用 JavaScript 在文档中写入然后下载该文档?
【发布时间】:2021-01-17 00:16:21
【问题描述】:

我如何使用 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

谢谢。

【问题讨论】:

    标签: javascript python file download


    【解决方案1】:

    您可以创建 Blob,。下面是一个示例,我已将结果放在这个 sn-p 的 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);

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-11
      • 1970-01-01
      • 2012-04-08
      • 2021-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-18
      相关资源
      最近更新 更多