这个
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()
破解一个---
window.showOpenFilePicker()
最后为此提供了更好的内置API,并且可配置性更强。还有一个
window.showSaveFilePicker
您希望实现“另存为”或“新文件”样式的功能。
-
这不会直接向我们提供文件的内容,而是提供
文件句柄
。这很有用,因为这意味着我们以后可以再次引用该文件(例如重写、删除、获取其元数据等)。
-
作为一种更好的用户体验(因此我们不会吓到人们!),我们只要求在他们点击保存按钮时能够保存文件,而不是直接保存。