如何让用户保存文件并仅在浏览器 Javascript 中继续编辑该文件?

How do I let user save a file and keep editing that file in browser Javascript only?

我认为由于 other on Whosebug. However, when I use the Diagram app at https://app.diagrams.net/ 中所述的安全原因,这是不可能的我在硬盘上的本地文件发生变化 (没有新的下载).

我知道只能 upload/download 一个文件并且相信你不能编辑它(使用 Blob 和 FileReader 等)。他们如何做到这一点?该应用程序是开源的,但不幸的是,通过 source code of their File Handler 我仍然无法找到他们使用的是什么 API。我不记得在浏览器中安装过任何插件或应用程序。

我还注意到我的浏览器中有此权限,所以我猜这是一些标准 API,但即使将其用作关键字,所有内容都会返回到 Whosebug 文章,说这是不可能的。

它是新的 API 我不知道吗?我在找什么?

您可以使用 localStorage 实现此目的,无需用户的任何其他许可。

localStorage.setItem("data", JSON.stringify(data));

如果您的数据只是 JSON 那么这会起作用,但是如果您有自定义数据类型,您可以查看 here.

编辑:

既然你想直接将文件保存到设备上并编辑它,你可以看看文件系统访问API。本文here对此进行了解释。

您可以先使用

加载文件
let fileHandle;
butOpenFile.addEventListener('click', async () => {
  [fileHandle] = await window.showOpenFilePicker();
  const file = await fileHandle.getFile();
  const contents = await file.text();
  textArea.value = contents;
});

获得文件句柄后,您应该能够写入文件,而无需在每次发生更改时请求下载新文件。

async function writeFile(fileHandle, contents) {
  // Create a FileSystemWritableFileStream to write to.
  const writable = await fileHandle.createWritable();
  // Write the contents of the file to the stream.
  await writable.write(contents);
  // Close the file and write the contents to disk.
  await writable.close();
}

代码来自我上面链接的文章,文章解释得非常清楚。值得一读。