FileSystemFileHandle

Baseline 广泛可用 *

此功能已成熟,并可在许多设备和浏览器版本上运行。自 2023 年 3 月以来,它已在各种浏览器中可用。

* 此特性的某些部分可能存在不同级别的支持。

安全上下文: 此功能仅在安全上下文(HTTPS)中可用,且支持此功能的浏览器数量有限。

注意:此功能在 Web Workers 中可用。

FileSystemFileHandle 接口是 文件系统 API 的一部分,代表一个文件系统条目的句柄。该接口可以通过 window.showOpenFilePicker() 方法访问。

请注意,读写操作取决于文件访问权限,如果同一来源的标签页不再打开,这些权限在页面刷新后将不会保留。可以使用 FileSystemHandle 接口的 queryPermission 方法在访问文件之前验证权限状态。

FileSystemHandle FileSystemFileHandle

实例属性

继承其父级 FileSystemHandle 的属性。

实例方法

继承其父级 FileSystemHandle 的方法。

getFile()

返回一个 Promise,该 Promise 解析为一个 File 对象,代表句柄所表示的条目在磁盘上的状态。

createSyncAccessHandle()

返回一个 Promise,该 Promise 解析为一个 FileSystemSyncAccessHandle 对象,该对象可用于同步地读写文件。此方法同步的特性带来了性能优势,但它只能在专用的 Web Workers 中使用。

createWritable()

返回一个 Promise,该 Promise 解析为一个新创建的 FileSystemWritableFileStream 对象,可用于写入文件。

示例

读取文件

以下异步函数显示一个文件选择器,一旦选择了一个文件,就会使用 getFile() 方法检索内容。

js
async function getTheFile() {
  const pickerOpts = {
    types: [
      {
        description: "Images",
        accept: {
          "image/*": [".png", ".gif", ".jpeg", ".jpg"],
        },
      },
    ],
    excludeAcceptAllOption: true,
    multiple: false,
  };

  // open file picker
  const [fileHandle] = await window.showOpenFilePicker(pickerOpts);
  // get file contents
  const fileData = await fileHandle.getFile();
  return fileData;
}

写入文件

以下异步函数将给定内容写入文件句柄,从而写入磁盘。

js
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();
}

同步读写文件

以下异步事件处理函数包含在 Web Worker 中。在接收到主线程的消息后,它会:

  • 创建一个同步文件访问句柄。
  • 获取文件大小并创建一个 ArrayBuffer 来存储它。
  • 将文件内容读入缓冲区。
  • 对消息进行编码并将其写入文件末尾。
  • 将更改持久化到磁盘并关闭访问句柄。
js
onmessage = async (e) => {
  // Retrieve message sent to work from main script
  const message = e.data;

  // Get handle to draft file
  const root = await navigator.storage.getDirectory();
  const draftHandle = await root.getFileHandle("draft.txt", { create: true });
  // Get sync access handle
  const accessHandle = await draftHandle.createSyncAccessHandle();

  // Get size of the file.
  const fileSize = accessHandle.getSize();
  // Read file content to a buffer.
  const buffer = new DataView(new ArrayBuffer(fileSize));
  const readBuffer = accessHandle.read(buffer, { at: 0 });

  // Write the message to the end of the file.
  const encoder = new TextEncoder();
  const encodedMessage = encoder.encode(message);
  const writeBuffer = accessHandle.write(encodedMessage, { at: readBuffer });

  // Persist changes to disk.
  accessHandle.flush();

  // Always close FileSystemSyncAccessHandle if done.
  accessHandle.close();
};

注意: 在规范的早期版本中,close()flush()getSize()truncate() 被错误地指定为异步方法,并且一些旧版本的浏览器以这种方式实现它们。然而,所有支持这些方法的当前浏览器都将其实现为同步方法。

规范

规范
文件系统
# api-filesystemfilehandle

浏览器兼容性

另见