如何拖放文件

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.getAsFile() 方法

DataTransferItem.getAsFile() 方法会返回拖动数据项的 File 对象。如果项不是文件,此方法会返回 null。虽然您可以读取文件,但无法对其进行回写。该方法的缺点是不支持目录。

浏览器支持

  • 11
  • 12
  • 50
  • 5.1

来源

渐进式增强

以下代码段会在新式 File System Access API 的 DataTransferItem.getAsFileSystemHandle() 方法受支持时使用该方法,然后回退到非标准 DataTransferItem.webkitGetAsEntry() 方法,最后回退到经典的 DataTransferItem.getAsFile() 方法。请务必检查每个 handle 的类型,因为它可以是以下任何一种:

  • FileSystemFileHandle(如果选择了新式代码路径)。
  • 如果选择了传统代码路径,则为 File

所有类型都具有 name 属性,因此可以正常记录数据,并且始终行之有效。

// Run feature detection.
const supportsFileSystemAccessAPI =
  'getAsFileSystemHandle' 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();
  // 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 `File`.
        : item.getAsFile(),
    );
  // Loop over the array of promises.
  for await (const handle of fileHandlesPromises) {
    // This is where we can actually exclusively act on the files.
    if (handle.kind === 'file' || handle.isFile) {
      console.log(`File: ${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 files</title>
  </head>
  <body>
    <main>
      <h1>How to drag and drop files</h1>
      <p>Drag and drop one or multiple files 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`;
    }
  }
});