How to Build a Drag-and-Drop File Upload
Build a drag-and-drop file upload with dragover and drop events, a file input fallback, validation, previews, folder drops and accessible feedback.

Dropping a file onto a page is faster than hunting through a file picker, and people have come to expect it for photos, documents and attachments. The browser provides the events and the data, and it takes little code to react to a drop, but the details decide whether it works: the drop zone must cancel the default behavior or the browser opens the file instead, the visual feedback must be clear, a normal file input must remain for keyboard and touch users, dropped files must be validated and previewed, folders need special handling and screen readers need to know what happened. This guide shows how to build a drag-and-drop file upload in JavaScript: the markup with a real input, the four drag events, preventing the browser's default file handling, reading dataTransfer.files, validation, drag-over feedback, previews, connecting the dropped files to the form and to an upload with progress, folders with webkitGetAsEntry, accessibility, mobile behavior and testing. The APIs are documented on MDN and are supported by all current browsers.
Start with a real file input
The drop zone should be an enhancement of a standard file input, not a replacement. A visible label wrapped around the input makes the whole zone clickable, which gives keyboard, touch and screen reader users the usual path.
<label id="drop-zone" class="drop-zone">
<span class="drop-zone__prompt">Drag files here or <u>browse</u></span>
<input id="file-input" type="file" multiple accept="image/*,.pdf" class="visually-hidden">
</label>
<ul id="file-list" aria-live="polite"></ul>.drop-zone {
display: grid;
place-items: center;
min-height: 10rem;
border: 2px dashed #9ca3af;
border-radius: 12px;
cursor: pointer;
}
.drop-zone.is-over {
border-color: #0b5fff;
background: rgb(11 95 255 / 0.08);
}
.drop-zone:focus-within {
outline: 3px solid #0b5fff;
outline-offset: 2px;
}
.visually-hidden {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip-path: inset(50%);
}(a dashed zone that opens the file picker on click and shows a focus ring for keyboard users)The input is visually hidden but stays focusable, so pressing Enter or Space when the label has focus through it opens the dialog. :focus-within shows the focus ring on the zone. Without script, this already works as a normal upload form.
Stop the browser from opening the file
By default, dropping a file on a page makes the browser navigate to it, replacing your app. To receive the drop, cancel the default of dragover, which signals that the element accepts drops, and of drop. It is a good idea to cancel the defaults on the whole window as well, so a miss does not navigate away.
for (const type of ["dragenter", "dragover", "dragleave", "drop"]) {
window.addEventListener(type, (event) => {
if (event.dataTransfer?.types?.includes("Files")) event.preventDefault();
});
}(a file dropped outside the zone is ignored instead of replacing the page)Checking that types includes Files leaves ordinary drags of text and links alone. Setting event.dataTransfer.dropEffect = "none" outside the zone shows the "not allowed" cursor.
The drag events
Four events matter. dragenter fires when a dragged item enters the zone, dragover fires repeatedly while it is over the zone, dragleave fires when it leaves and drop fires on release. Use them to toggle a class for feedback and to receive the files.
const zone = document.querySelector("#drop-zone");
const input = document.querySelector("#file-input");
let depth = 0;
zone.addEventListener("dragenter", (event) => {
event.preventDefault();
depth += 1;
zone.classList.add("is-over");
});
zone.addEventListener("dragover", (event) => {
event.preventDefault();
event.dataTransfer.dropEffect = "copy";
});
zone.addEventListener("dragleave", () => {
depth -= 1;
if (depth <= 0) {
depth = 0;
zone.classList.remove("is-over");
}
});
zone.addEventListener("drop", (event) => {
event.preventDefault();
depth = 0;
zone.classList.remove("is-over");
handleFiles([...event.dataTransfer.files]);
});(the zone highlights while a file is over it, and the files are handled on drop)The counter depth solves a well-known annoyance: dragenter and dragleave also fire when the pointer crosses the zone's child elements, so a plain add on enter and remove on leave makes the highlight flicker. Counting enters and leaves keeps it steady. Setting dropEffect to "copy" shows the plus cursor.
Read and validate the files
event.dataTransfer.files is a FileList of File objects, which you can check by name, type and size. Accept what fits, and tell the user plainly about the rest.
const MAX_BYTES = 10 * 1024 * 1024;
const ALLOWED = ["image/png", "image/jpeg", "image/webp", "application/pdf"];
function handleFiles(files) {
const accepted = [];
const rejected = [];
for (const file of files) {
if (!ALLOWED.includes(file.type)) rejected.push(`${file.name}: type not allowed`);
else if (file.size > MAX_BYTES) rejected.push(`${file.name}: larger than 10 MB`);
else accepted.push(file);
}
render(accepted);
if (rejected.length) announce(`Skipped ${rejected.length} file(s): ${rejected.join("; ")}`);
return accepted;
}
function announce(message) {
document.querySelector("#status").textContent = message;
}Skipped 1 file(s): notes.exe: type not allowedThe type is derived from the extension, so it is a convenience check, and the server must validate the real contents. Cap the number of files if the interface cannot handle many, and remove duplicates by name and size if that matters.
Show the list and previews
Display each accepted file with its name and size, and a thumbnail for images made with an object URL. Give users a way to remove a file before upload.
const selected = new Map();
function render(newFiles) {
for (const file of newFiles) selected.set(`${file.name}:${file.size}`, file);
const list = document.querySelector("#file-list");
list.replaceChildren(
...[...selected].map(([key, file]) => {
const li = document.createElement("li");
const label = document.createElement("span");
label.textContent = `${file.name} (${Math.round(file.size / 1024)} KB)`;
const remove = document.createElement("button");
remove.type = "button";
remove.textContent = "Remove";
remove.setAttribute("aria-label", `Remove ${file.name}`);
remove.addEventListener("click", () => {
selected.delete(key);
render([]);
});
li.append(label, remove);
return li;
}),
);
}(each file appears with a Remove button, and the list is a live region)The list is an aria-live="polite" region, so screen reader users hear that files were added. Revoke any object URLs you create for thumbnails, as covered in the guide on previewing images.
Connect it to the form
Both the drop and the picker should lead to the same state. For a plain form submission, put the dropped files into the input with a DataTransfer, since a FileList is read-only, and the browser then submits them as usual.
function setInputFiles(files) {
const transfer = new DataTransfer();
files.forEach((file) => transfer.items.add(file));
input.files = transfer.files;
}
input.addEventListener("change", () => handleFiles([...input.files]));
zone.addEventListener("drop", (event) => {
event.preventDefault();
const accepted = handleFiles([...event.dataTransfer.files]);
setInputFiles(accepted);
});(a submitted form includes the dropped files, as if they had been chosen with the picker)If you upload with fetch or XMLHttpRequest, append the files from your selected map to a FormData instead, and keep the input only as a way to add more. Either way, keep one source of truth for the list.
Upload
Send the files with the techniques in the guide on uploading with progress: a FormData body, a request per file or one for all and a progress element for each. Disable the drop zone while an upload is running, or queue the new files, and give clear feedback when each completes or fails.
async function uploadAll() {
for (const file of selected.values()) {
const form = new FormData();
form.append("file", file);
const response = await fetch("/api/files", { method: "POST", body: form });
announce(response.ok ? `${file.name} uploaded` : `${file.name} failed (${response.status})`);
}
}photo.png uploadedFolders
Dropping a folder gives you an entry, not a file, and dataTransfer.files lists it with an empty type, which would fail to upload. To read the contents, use dataTransfer.items and the webkitGetAsEntry() method, which despite the prefix is supported across current browsers, and walk the directory tree.
async function readEntry(entry, path = "") {
if (entry.isFile) {
const file = await new Promise((resolve, reject) => entry.file(resolve, reject));
return [{ file, path: path + file.name }];
}
const reader = entry.createReader();
const results = [];
while (true) {
const batch = await new Promise((resolve, reject) => reader.readEntries(resolve, reject));
if (batch.length === 0) break;
for (const child of batch) results.push(...(await readEntry(child, `${path}${entry.name}/`)));
}
return results;
}
zone.addEventListener("drop", async (event) => {
event.preventDefault();
const entries = [...event.dataTransfer.items].map((item) => item.webkitGetAsEntry()).filter(Boolean);
const all = (await Promise.all(entries.map((entry) => readEntry(entry)))).flat();
console.log(all.map((item) => item.path));
});[ 'photos/a.jpg', 'photos/b.jpg', 'photos/2026/c.jpg' ]readEntries() returns results in batches, so the loop continues until it gives an empty batch. Capture the entries synchronously in the event handler before any await, because the dataTransfer data is cleared after the handler returns. Limit the depth and count to avoid a huge drop freezing the page.
Accessibility
Drag and drop cannot be the only way, as it is difficult or impossible for keyboard, switch and many screen reader users. The visible label with the file input provides the alternative, and it must be obvious. Announce the result of an action in a live region: "3 files added", and the errors. Make the instruction text visible, and ensure contrast for the dashed border and highlighted state. Do not rely on color alone to show the active state. Provide the same remove and retry controls by keyboard.
Mobile
Touch devices have no drag and drop of files in most browsers, so the input is what they use, and accept along with capture can open the camera. Do not hide the "browse" text on small screens, and avoid wording like "drop" when there is no way to do it. Detect support if you want to vary the message, with "draggable" in document.createElement("div") and the pointer media queries from the earlier guide.
Test it
In automated tests, a browser driver can set files on the input directly, which exercises the validation and the upload code. To test the drop handlers, dispatch a synthetic drop event with a DataTransfer that contains a File.
const data = new DataTransfer();
data.items.add(new File(["hello"], "note.pdf", { type: "application/pdf" }));
zone.dispatchEvent(new DragEvent("drop", { dataTransfer: data, bubbles: true, cancelable: true }));
console.log(selected.size);1Also drag real files from the desktop in each target browser, try dropping outside the zone, dropping a folder, dropping something that is not a file such as selected text, canceling a drag by pressing Escape and using only the keyboard.


