【问题标题】:How to use FileSaver.js to save text files如何使用 FileSaver.js 保存文本文件
【发布时间】:2018-05-02 01:39:58
【问题描述】:

我在 github 上下载了 FilSaver.js 并尝试对其进行测试以供将来使用。我制作了一个简单的 html 文件,该文件接受输入,当单击按钮时触发一个函数,该函数将使用 FileSaver 保存文件.js。

在文件夹中我只有 FileSaver.js 和 HTML 文件。

这是我的代码。

<html>
    <head>

    </head>
    <body>
        <input type="text" id="sample">
        <button id="button" onclick="download();">save as</button>

        <script src="FileSaver.js"></script>
        <script type="text/javascript">
            function download(){
            var save = document.getElementById("sample").value;
            alert(save);    
            var blob = new Blob([save], {type: "text/plain;charset=utf-8"});
            saveAs(blob, "hello world.txt");}
        </script>
    </body>
</html>

错误:

-Uncaught SyntaxError: Unexpected token export on this line of code inside the FileSaver.js var saveAs = saveAs || (功能(视图){

-lol.html:15 Uncaught ReferenceError: saveAs is not defined on this line code inside the html file saveAs(blob, "hello world.txt");}

【问题讨论】:

  • 在他们的网站示例中,他们使用了您不包括在内的 Blob.js....
  • @DanielTate 我添加了我在演示中看到的所有脚本,但它仍然无法正常工作。
  • @Kaiido 我添加了我遇到的错误,我正在使用 Opera
  • 您的代码 100% 有效jsfiddle.net/1pr4090t
  • @DanielTate 这很奇怪它对我不起作用。

标签: javascript html


【解决方案1】:

只需更新到以下内容即可,请尝试以下演示中用于文件保护程序的 CDN 服务器

function download() {
  var save = document.getElementById("sample").value;
  var blob = new Blob([save], {
    type: "text/plain;charset=utf-8"
  });
  saveAs(blob, "sample-file.txt");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.rawgit.com/eligrey/FileSaver.js/5ed507ef8aa53d8ecfea96d96bc7214cd2476fd2/FileSaver.min.js"></script>
<input type="text" id="sample">
<button id="button" onclick="download();">save as</button>

【讨论】:

  • 非常感谢老兄。
猜你喜欢
  • 1970-01-01
  • 2013-04-11
  • 1970-01-01
  • 2013-10-31
  • 2019-04-09
  • 1970-01-01
  • 2013-12-21
  • 1970-01-01
  • 2023-03-13
相关资源
最近更新 更多