【问题标题】:How can I save changes to a file selected from the user's computer in JavaScript?如何使用 JavaScript 保存对从用户计算机中选择的文件所做的更改?
【发布时间】:2022-12-10 16:21:42
【问题描述】:
许多现代网络应用程序和 PWA 允许用户从他们的硬盘驱动器中选择一个文件,然后直接将更改保存回该文件.
一种老式的方法是读取文件,在服务器端进行必要的更改,然后将用户发送到一个页面,他们可以在该页面下载新文件。然而,新一代的网络应用程序能够直接保存更改(无需下载),并且无需任何服务器参与。
这怎么可能,我怎样才能实现类似的东西?
【问题讨论】:
标签:
javascript
file-system-access-api
filesystem-access
【解决方案1】:
File System Access API 允许您打开和读取用户计算机上的文件(甚至整个目录!),然后写回您的更改。如果您选择打开一个目录,它甚至可以在该目录中创建和删除新文件和文件夹!
对这个 API can be found on Chrome's website 的一个很好的介绍。否则,这里有一个简单的例子,说明如何读取单个文件,然后直接将更改保存回来:
let fileHandle;
async function openFile() {
[fileHandle] = await window.showOpenFilePicker();
// we don't want to handle e.g. folders in this example
if (fileHandle.kind !== "file") {
alert("Please select a file, not a folder");
return;
}
const file = await fileHandle.getFile();
const contents = await file.text();
document.querySelector("#contents").value = contents;
}
async function saveFile() {
// Request permission to edit the file
await fileHandle.requestPermission({ mode: "readwrite" });
const writable = await fileHandle.createWritable();
await writable.write(document.querySelector("#contents").value);
await writable.close();
}
document.querySelector("#openButton").addEventListener("click", openFile);
document.querySelector("#saveButton").addEventListener("click", saveFile);
<p>
<strong>Note: this does work, but StackOverflow's snippets block access to this API--- try it out on your local machine</strong>
</p>
<div>
<button id="openButton">Open</button>
<button id="saveButton">Save</button>
</div>
<textarea id="contents"></textarea>
关键点:
- 我们不使用
<input type="file" /> 或旧的 .click() hack 来打开一个 --- window.showOpenFilePicker() 终于为此提供了一个更好的内置 API,并且可配置性更高。还有一个 window.showSaveFilePicker 您想实现“另存为”或“新文件”样式的功能。
- 这并没有直接给我们文件的内容,而是一个文件句柄.这很有用,因为这意味着我们稍后可以再次引用该文件(例如,覆盖它、删除它、获取它的元数据等)。
- 作为更好的用户体验(因此我们不会吓到人们!),我们只要求在他们单击保存按钮时保存文件,而不是立即保存。