如何在iOS Safari上使用JavaScript下载JSON文件

7

我阅读了很多关于这个主题的内容,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: attachment; filename="filename.jpg"将其反映回客户端。 - ibrahim tanyalcin
你是否将 Content-Type 设置为 application/octet-stream,并将 Content-Disposition 设置为 attachment; filename="filename.jpg"?这样应该可以了,似乎 Safari 终于允许任意下载了。 - Owen Versteeg
1个回答

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。 - greg-tumolo
1
谢谢你。这是我用来验证的jsfiddle链接:https://jsfiddle.net/bkjte6Lh/ - codepleb

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接