如何拖曳目錄

湯馬斯 (Thomas Steiner)
Thomas Steiner

HTML 拖曳介面可讓網頁應用程式接受拖曳和捨棄的檔案。在拖曳作業期間,拖曳的檔案和目錄項目會分別與檔案項目和目錄項目建立關聯。如要將檔案拖曳至瀏覽器,有兩種方法可供選擇:新式與傳統。

新穎時尚

使用 File System Access API 的 DataTransferItem.getAsFileSystemHandle() 方法

如果拖曳的項目是檔案,DataTransferItem.getAsFileSystemHandle() 方法會傳回具有 FileSystemFileHandle 物件的 Commit,如果拖曳項目為目錄,則會傳回 FileSystemDirectoryHandle 物件的保證。這些控點可讓您讀取檔案或目錄,並視需要寫入。請注意,「拖曳」介面的 DataTransferItem.kind 會是檔案「和」目錄的 "file",而 File System Access API 的 FileSystemHandle.kind 則是 "file" 的檔案,而目錄則為 "directory"

瀏覽器支援

  • 86
  • 86
  • x
  • x

資料來源

經典風格

使用非標準 DataTransferItem.webkitGetAsEntry() 方法

如果項目是檔案,DataTransferItem.webkitGetAsEntry() 方法會傳回拖曳資料項目的 FileSystemFileEntry,如果項目是目錄,則傳回 FileSystemDirectoryEntry。您雖然可以讀取檔案或目錄,但無法寫回這些內容。這種方法的缺點是不符合標準測試群組,但具有支援目錄的優勢。

瀏覽器支援

  • 13
  • 14
  • 50
  • 11.1

資料來源

漸進增強

下列程式碼片段在支援的情況下使用新型 File System Access API 的 DataTransferItem.getAsFileSystemHandle() 方法,接著改回非標準 DataTransferItem.webkitGetAsEntry() 方法,最後改回使用傳統 DataTransferItem.getAsFile() 方法。請務必檢查每個 handle 的類型,因為其類型可能為:

  • 選擇新式程式碼路徑時,FileSystemDirectoryHandle
  • 選擇非標準程式碼路徑時,FileSystemDirectoryEntry

所有類型都有 name 屬性,因此記錄功能正確無誤,能隨時正常運作。

// Run feature detection.
const supportsFileSystemAccessAPI =
  'getAsFileSystemHandle' in DataTransferItem.prototype;
const supportsWebkitGetAsEntry =
  'webkitGetAsEntry' in DataTransferItem.prototype;

// This is the drag and drop zone.
const elem = document.querySelector('main');

// Prevent navigation.
elem.addEventListener('dragover', (e) => {
  e.preventDefault();
});

// Visually highlight the drop zone.
elem.addEventListener('dragenter', (e) => {
  elem.style.outline = 'solid red 1px';
});

// Visually unhighlight the drop zone.
elem.addEventListener('dragleave', (e) => {
  elem.style.outline = '';
});

// This is where the drop is handled.
elem.addEventListener('drop', async (e) => {
  // Prevent navigation.
  e.preventDefault();
  if (!supportsFileSystemAccessAPI && !supportsWebkitGetAsEntry) {
    // Cannot handle directories.
    return;
  }
  // Unhighlight the drop zone.
  elem.style.outline = '';

  // Prepare an array of promises…
  const fileHandlesPromises = [...e.dataTransfer.items]
    // …by including only files (where file misleadingly means actual file _or_
    // directory)…
    .filter((item) => item.kind === 'file')
    // …and, depending on previous feature detection…
    .map((item) =>
      supportsFileSystemAccessAPI
        // …either get a modern `FileSystemHandle`…
        ? item.getAsFileSystemHandle()
        // …or a classic `FileSystemFileEntry`.
        : item.webkitGetAsEntry(),
    );
  // Loop over the array of promises.
  for await (const handle of fileHandlesPromises) {
    // This is where we can actually exclusively act on the directories.
    if (handle.kind === 'directory' || handle.isDirectory) {
      console.log(`Directory: ${handle.name}`);
    }
  }
});

其他資訊

示範

HTML

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>How to drag and drop directories</title>
  </head>
  <body>
    <main>
      <h1>How to drag and drop directories</h1>
      <p>Drag and drop one or multiple files or directories onto the page.</p>
      <pre></pre>
    </main>
  </body>
</html>

CSS


        :root {
  color-scheme: dark light;
  box-sizing: border-box;
}

*,
*:before,
*:after {
  box-sizing: inherit;
}

body {
  margin: 0;
  padding: 1rem;
  font-family: system-ui, sans-serif;
  line-height: 1.5;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

img,
video {
  height: auto;
  max-width: 100%;
}

main {
  flex-grow: 1;
}

footer {
  margin-top: 1rem;
  border-top: solid CanvasText 1px;
  font-size: 0.8rem;
}
        

JS


        const supportsFileSystemAccessAPI =
  "getAsFileSystemHandle" in DataTransferItem.prototype;
const supportsWebkitGetAsEntry =
  "webkitGetAsEntry" in DataTransferItem.prototype;

const elem = document.querySelector("main");
const debug = document.querySelector("pre");

elem.addEventListener("dragover", (e) => {
  // Prevent navigation.
  e.preventDefault();
});

elem.addEventListener("dragenter", (e) => {
  elem.style.outline = "solid red 1px";
});

elem.addEventListener("dragleave", (e) => {
  elem.style.outline = "";
});

elem.addEventListener("drop", async (e) => {
  e.preventDefault();
  elem.style.outline = "";
  const fileHandlesPromises = [...e.dataTransfer.items]
    .filter((item) => item.kind === "file")
    .map((item) =>
      supportsFileSystemAccessAPI
        ? item.getAsFileSystemHandle()
        : supportsWebkitGetAsEntry
        ? item.webkitGetAsEntry()
        : item.getAsFile()
    );

  for await (const handle of fileHandlesPromises) {
    if (handle.kind === "directory" || handle.isDirectory) {
      console.log(`Directory: ${handle.name}`);
      debug.textContent += `Directory: ${handle.name}\n`;
    } else {
      console.log(`File: ${handle.name}`);
      debug.textContent += `File: ${handle.name}\n`;
    }
  }
});