DataTransferItem:getAsFileSystemHandle() 方法

可用性有限

此特性不是基線特性,因為它在一些最廣泛使用的瀏覽器中不起作用。

安全上下文: 此功能僅在安全上下文(HTTPS)中可用,且支援此功能的瀏覽器數量有限。

實驗性: 這是一項實驗性技術
在生產中使用此技術之前,請仔細檢查瀏覽器相容性表格

DataTransferItem 介面的 getAsFileSystemHandle() 方法返回一個 Promise,如果拖動的項是檔案,則該 Promise fulfilled 為 FileSystemFileHandle,如果拖動的項是目錄,則 fulfilled 為 FileSystemDirectoryHandle

語法

js
getAsFileSystemHandle()

引數

無。

返回值

Promise

如果項的 kind 屬性為 "file",並且在 dragstartdrop 事件處理程式中訪問此項,那麼如果拖動的項是檔案,返回的 Promise fulfilled 為 FileSystemFileHandle;如果拖動的項是目錄,則 fulfilled 為 FileSystemDirectoryHandle

否則,Promise fulfilled 為 null

異常

無。

示例

此示例使用 getAsFileSystemHandle() 方法為拖放的項返回 檔案控制代碼

注意: 因為 getAsFileSystemHandle() 只能在 drop 事件處理程式的同一個 tick 中檢索入口控制代碼,所以在此之前不能有 await。這就是為什麼我們首先同步地為所有項呼叫 getAsFileSystemHandle(),然後併發等待它們的結果。

js
elem.addEventListener("dragover", (e) => {
  // Prevent navigation.
  e.preventDefault();
});
elem.addEventListener("drop", async (e) => {
  // Prevent navigation.
  e.preventDefault();
  const handlesPromises = [...e.dataTransfer.items]
    // kind will be 'file' for file/directory entries.
    .filter((x) => x.kind === "file")
    .map((x) => x.getAsFileSystemHandle());
  const handles = await Promise.all(handlesPromises);

  // Process all of the items.
  for (const handle of handles) {
    if (handle.kind === "file") {
      // run code for if handle is a file
    } else if (handle.kind === "directory") {
      // run code for is handle is a directory
    }
  }
});

規範

規範
檔案系統訪問
# dom-datatransferitem-getasfilesystemhandle

瀏覽器相容性

另見