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

瀏覽器相容性

另見