【问题标题】:How to download a JSON file with javascript on iOS Safari?如何在 iOS Safari 上使用 javascript 下载 JSON 文件?
【发布时间】:2020-10-04 07:05:51
【问题描述】:

我阅读了很多关于这个主题的内容,Safari 似乎对此有疑问(甚至是 filesaver.js)。我仍然想知道,你们是否有一种方法可以让用户单击按钮并将带有文件名的 json 文件下载到他的设备。

那里有很多线程,Safari 过去似乎遇到过问题,这些问题已经解决。但目前的 safari 版本似乎仍然无法做到这一点。我把最后的希望寄托在你们身上。对最新版本的 iOS 更新没有帮助。

这是我的方法,适用于 Safari 桌面:

    exportButton.addEventListener("click", () => {
      const appState = databaseConnector.getApplicationStateAsString();
      const blob = new Blob([appState], { type: "text/json" });
      const fileName = `backup_${
        new Date().toISOString().split("T")[0]
      }.json`;

      const tempElement = document.createElement("a");
      const url = URL.createObjectURL(blob);
      tempElement.href = url;
      tempElement.download = fileName;
      document.body.appendChild(tempElement);
      tempElement.click();

      setTimeout(function () {
        document.body.removeChild(tempElement);
        window.URL.revokeObjectURL(url);
      });
    });

【问题讨论】:

  • 我有一个网站,它使用类似的东西,它可以工作,我在下载文件夹中看到文件。当前 Safari 版本无法下载的说法是不正确的。在最坏的情况下,将数据发送回服务器并使用正确的 Content-Type 标头和 Content-Disposition: 附件将其反射回客户端;文件名="文件名.jpg"
  • 您是否将 Content-Type 设置为 application/octet-stream 并将 Content-Disposition 设置为 ` attachment;文件名="文件名.jpg" `?应该可以,看来 Safari 终于允许任意下载了。

标签: javascript ios safari mobile-safari filesaver.js


【解决方案1】:

试试下面的代码。

<!DOCTYPE html>
<title>Answer</title>
<a id=a download=answer.json href style=-webkit-appearance:button;color:black;text-decoration:none>Download</a>
<script>
a.href = "data:text/json;," + JSON.stringify({name: "answer"})
</script>

【讨论】:

  • 使用 JSON.parse 撤消 JSON.stringify。
  • 谢谢你。这是我用来验证它的jsfiddle:jsfiddle.net/bkjte6Lh
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-28
  • 1970-01-01
  • 2017-11-28
  • 1970-01-01
  • 1970-01-01
  • 2015-05-21
  • 2017-07-18
相关资源
最近更新 更多