# FileSystemHandle

> FileSystemHandle 表示文件或目录条目，并提供种类、名称、条目比较和权限方法。

`FileSystemHandle` 接口表示文件或目录条目。只读属性 `kind` 和 `name` 描述条目，`isSameEntry()` 用来判断另一句柄是否表示同一条目（[File System Standard](https://fs.spec.whatwg.org/#api-filesystemhandle)）。

## 支持范围

BCD `api.FileSystemHandle` 记录的核心接口支持始于 Chrome 86、Android 版 Chrome 109、Firefox 111 和 Safari 15.2；相关浏览器使用 BCD 的镜像记录。File System Standard 规定此接口只在安全上下文中暴露给 `Window` 和 worker，并且可以序列化。

权限方法的支持范围较窄。BCD 对 `api.FileSystemHandle.queryPermission` 和 `api.FileSystemHandle.requestPermission` 的记录始于 Chrome 86、Android 版 Chrome 109，Firefox 和 Safari 均记为不支持。

## 语法

```js
handle.kind
handle.name

await handle.isSameEntry(otherHandle)
await handle.queryPermission()
await handle.queryPermission({ mode: "readwrite" })
await handle.requestPermission()
await handle.requestPermission({ mode: "readwrite" })
```

File System Standard 定义 `kind`、`name` 和 `isSameEntry()`。File System Access 草案用 partial interface 补充 `queryPermission()` 与 `requestPermission()`。如果代码接收来自多种入口的句柄，调用权限方法前应先检查方法是否存在。

## 成员

核心接口定义 `kind`、`name` 和 `isSameEntry()`。`FileSystemFileHandle` 与 `FileSystemDirectoryHandle` 继承这些成员；应用通常从浏览器 API 获得这些派生句柄，不会自行构造 `FileSystemHandle`（[FileSystemHandle](https://developer.mozilla.org/en-US/docs/Web/API/FileSystemHandle)，MDN）。

| 成员 | 类型 | 说明 |
|---|---|---|
| `kind` | `"file" \| "directory"` | 表示条目是文件还是目录。 |
| `name` | `USVString` | 返回条目名称。名称不是条目的身份：标准允许多个句柄共用同一个定位符，不同目录也可能含有同名条目。 |
| `isSameEntry(other)` | `Promise<boolean>` | 两个句柄拥有同一文件系统定位符时兑现为 `true`，否则兑现为 `false`。 |

File System Access 草案为使用本地文件权限模型的句柄补充了以下方法。

| 成员 | 参数 | 结果 | 说明 |
|---|---|---|---|
| `queryPermission(descriptor)` | 可选 `{ mode: "read" \| "readwrite" }`；`mode` 默认为 `"read"` | `Promise<"granted" \| "denied" \| "prompt">` | 返回权限状态，不向用户发起请求（[queryPermission()](https://wicg.github.io/file-system-access/#api-filesystemhandle-querypermission)）。 |
| `requestPermission(descriptor)` | 可选 `{ mode: "read" \| "readwrite" }`；`mode` 默认为 `"read"` | `Promise<"granted" \| "denied" \| "prompt">` | 对于 `{ mode: "readwrite" }`，即使写权限为 `"prompt"`，只要读权限为 `"denied"`，也会直接返回 `"denied"`，不执行权限请求算法。除此之外，非 `"prompt"` 状态会直接返回，`"prompt"` 状态会执行权限请求算法（[requestPermission()](https://wicg.github.io/file-system-access/#api-filesystemhandle-requestpermission)）。 |

句柄可以来自 `navigator.storage.getDirectory()` 所取得的源私有文件系统，也可以来自本地选择器或拖放条目。核心成员不会显示句柄来自哪条路径。WICG 草案规定，bucket 文件系统内条目的权限状态为 `"granted"`；当句柄指向 bucket 外的条目时，权限扩展才会参与访问判断。

`isSameEntry()` 的比较对象是条目本身，不会比较名称字符串。保存过的句柄与新获得的句柄可能指向同一文件，此时应调用该方法。只比较 `name` 无法确认身份，因为标准把身份关联到定位符。

## 异常

标准中的 `isSameEntry()` 算法用布尔值兑现 Promise。`requestPermission()` 遇到 `"prompt"` 状态，需要真正发起权限请求，此时还要满足额外条件。

| 操作 | 失败情况 |
|---|---|
| 在 worker 中对 `"prompt"` 状态调用 `requestPermission()` | 权限请求算法要求全局对象是 `Window`，因此以 `SecurityError` 拒绝。 |
| 没有瞬时用户激活时对 `"prompt"` 状态调用 `requestPermission()` | 以 `SecurityError` 拒绝。应在点击或其他带用户激活的操作中调用。 |
| 在与顶层页面不同源的 frame 中对 `"prompt"` 状态调用 `requestPermission()` | 以 `SecurityError` 拒绝。 |
| 默认的读取权限查询返回 `"denied"` 后操作句柄 | WICG 草案说明，对该句柄的任何操作都会拒绝。`{ mode: "readwrite" }` 查询的是写权限，因此其结果为 `"denied"` 并不能说明读权限也被拒绝。 |

:::caution
[`requestPermission()` 权限请求算法](https://wicg.github.io/file-system-access/#api-filesystemhandle-requestpermission)（wicg.github.io）规定，需要提示时，全局对象不是 `Window`、没有瞬时用户激活，或当前源与顶层源不同都会抛出 `SecurityError`。把调用留在「恢复访问」按钮的点击处理器中。如果挪到启动代码或 worker，权限算法要求的条件便不成立。
:::

## 示例

核心成员可直接用于源私有文件系统句柄。使用 Chromium 的权限扩展时，需要单独检测功能；选择器或权限不可用时，改走 `<input type="file">` 和下载路径。

### 比较句柄，不依赖名称判断

把以下代码放到安全上下文页面中。点击「比较句柄」，代码会重复取得 `draft.txt`，再取得 `archive.txt`，然后比较这些句柄。如果 `navigator.storage.getDirectory()` 不可用，文件输入仍能让用户选择文件，并显示 `File` 对象可提供的元数据。

```html
<button id="compare">比较句柄</button>
<input id="file-fallback" type="file" hidden>
<pre id="result"></pre>
<script type="module">
  const result = document.querySelector("#result");
  const fallback = document.querySelector("#file-fallback");

  document.querySelector("#compare").addEventListener("click", async () => {
    if (!("storage" in navigator) || !("getDirectory" in navigator.storage)) {
      fallback.hidden = false;
      fallback.click();
      return;
    }
    const root = await navigator.storage.getDirectory();
    const first = await root.getFileHandle("draft.txt", { create: true });
    const second = await root.getFileHandle("draft.txt");
    const other = await root.getFileHandle("archive.txt", { create: true });
    result.textContent = JSON.stringify({
      first: { name: first.name, kind: first.kind },
      sameDraft: await first.isSameEntry(second),
      sameAsArchive: await first.isSameEntry(other),
    }, null, 2);
  });

  fallback.addEventListener("change", () => {
    const file = fallback.files[0];
    result.textContent = file ? `${file.name} (${file.type || "未知类型"})` : "未选择文件";
  });
</script>
```

按标准的定位符比较规则，预期 `sameDraft` 为 `true`，`sameAsArchive` 为 `false`。若要清理创建的 OPFS 条目，可以分别调用 `root.removeEntry("draft.txt")` 和 `root.removeEntry("archive.txt")`。

### 写权限被拒后改为下载副本

这个完整示例只在按钮点击后请求本地文件。「请求写权限」按钮检查写权限；状态为 `"prompt"` 时，它从自己的点击处理器调用 `requestPermission()`。浏览器不支持选择器或用户拒绝权限时，页面显示文件输入。用户选中文件后会得到可下载的副本，回退路径会实际交付文件，不会只显示提示。

```html
<button id="choose">选择本地文件</button>
<button id="write" disabled>请求写权限</button>
<input id="copy-source" type="file" hidden>
<output id="status"></output>
<script type="module">
  let handle;
  const write = document.querySelector("#write");
  const source = document.querySelector("#copy-source");
  const status = document.querySelector("#status");

  function useDownloadFallback() {
    source.hidden = false;
    source.focus();
    status.value = "请在下方选择文件并下载副本";
  }

  document.querySelector("#choose").addEventListener("click", async () => {
    if (!("showOpenFilePicker" in window)) return useDownloadFallback();
    try {
      [handle] = await window.showOpenFilePicker();
      if (!("queryPermission" in handle) || !("requestPermission" in handle)) {
        return useDownloadFallback();
      }
      write.disabled = false;
      status.value = `已选择 ${handle.name}`;
    } catch (error) {
      if (error.name !== "AbortError") throw error;
      status.value = "未选择文件";
    }
  });

  write.addEventListener("click", async () => {
    try {
      let state = await handle.queryPermission({ mode: "readwrite" });
      if (state === "prompt") {
        state = await handle.requestPermission({ mode: "readwrite" });
      }
      status.value = `写权限：${state}`;
      if (state !== "granted") useDownloadFallback();
    } catch (error) {
      status.value = `${error.name}：请另选文件并下载副本`;
      useDownloadFallback();
    }
  });

  source.addEventListener("change", () => {
    const file = source.files[0];
    if (!file) return;
    const link = document.createElement("a");
    link.href = URL.createObjectURL(file);
    link.download = `copy-${file.name}`;
    link.click();
    URL.revokeObjectURL(link.href);
    status.value = `已下载 copy-${file.name}`;
  });
</script>
```

Chrome 的文件访问文档建议先查询已保存句柄的权限，需要时再请求权限（[Stored file or directory handles and permissions](https://developer.chrome.com/docs/capabilities/web-apis/file-system-access#stored-file-or-directory-handles-and-permissions)，Chrome for Developers）。上例从用户操作中发起请求，并让回退流程脱离已经失去访问权的句柄。

## 另请参阅

- [File System Access API](/zh/reference/capabilities/file-system-access/)，用于打开和保存用户选择的文件
- [Origin Private File System（OPFS，源私有文件系统）](/zh/reference/storage/opfs/)，用于取得以源私有 bucket 为根的句柄
- [处理文件](/zh/guides/file-handling/)，用于完成文件编辑流程
- [File System Access 兼容性数据](/zh/compatibility/file-system-access/)，用于查看本地选择器入口的实测支持数据
- [File System Standard: FileSystemHandle interface](https://fs.spec.whatwg.org/#api-filesystemhandle)（fs.spec.whatwg.org）
- [File System Access: FileSystemHandle permission extension](https://wicg.github.io/file-system-access/#api-filesystemhandle-querypermission)（wicg.github.io）
- [The File System Access API: simplifying access to local files](https://developer.chrome.com/docs/capabilities/web-apis/file-system-access)（developer.chrome.com）