如何拖放目录

Thomas Steiner
Thomas Steiner

借助 HTML 拖放界面,Web 应用可以在网页上接受拖放的文件。在拖放操作期间,拖动的文件和目录项会分别与文件条目和目录条目相关联。将文件拖放到浏览器中有两种方法:现代和经典。

现代风

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

如果拖动的项是文件,DataTransferItem.getAsFileSystemHandle() 方法会返回一个带有 FileSystemFileHandle 对象的 promise;如果拖动的项是目录,则返回带有 FileSystemDirectoryHandle 对象的 promise。通过这些句柄,您可以读取文件或选择写回这些句柄。请注意,拖放接口的 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`;
    }
  }
});