Folder Drop Support
What you'll learn: How to detect and handle entire folder drops in modern browsers using DataTransferItem and webkitGetAsEntry.
When users drag-and-drop folders onto your web page, browsers don't automatically give you all the files inside. You need to explicitly request folder entries and recursively traverse their contents—a capability that's available through the DataTransferItem interface and the (still prefixed) webkitGetAsEntry() method.
How It Works
Instead of directly accessing dataTransfer.files on drop (which only gives you the immediate files, not folders), you iterate through dataTransfer.items. Each item has a webkitGetAsEntry() method that returns either a FileSystemFileEntry or a FileSystemDirectoryEntry.
Think of it like this: The standard drop API hands you only the "envelopes" users dropped. With webkitGetAsEntry(), you can open those envelopes to see if they're single letters (files) or entire filing cabinets (folders) that you need to explore drawer-by-drawer.
Traversing Directories
When you detect a directory entry, you call its createReader() method to get a reader, then use readEntries() to list its contents. For each nested item, you check if it's a file or another directory, handling files and recursing into subdirectories.
async function traverseDirectory(entry, path = '') {
if (entry.isFile) {
entry.file(file => console.log(`${path}/${file.name}`));
} else if (entry.isDirectory) {
const reader = entry.createReader();
reader.readEntries(entries => {
entries.forEach(e => traverseDirectory(e, `${path}/${entry.name}`));
});
}
}
Key Takeaway: Use DataTransferItem.webkitGetAsEntry() to detect folder drops and recursively traverse directory structures, enabling users to upload entire project folders in supported browsers.