JavaScript Drag and Drop File Upload with HTML5 API
Implement native HTML5 drag and drop file upload in JavaScript — drop zones, file validation, upload progress and image previews without libraries.
Overview
Getting files into a web app usually means opening a file picker dialog. The HTML5 Drag and Drop API is the browser’s built-in way to drag files and data onto page elements — it adds the nicer path: users drag files straight onto your page, no third-party library needed. This recipe builds a drop zone step by step: it validates files by type and size, uploads them with FormData while tracking progress, and gives visual feedback while the user drags.
When to Use
- You need a file upload area where users can drop files instead of clicking a button
- You want to reject invalid files client-side before they hit your server
- You need upload progress feedback for large files
- You’re building an image gallery uploader or a document management UI
- Skip it when your audience is mostly mobile — drag and drop barely works on touch screens, so a plain
<input type="file">is the better default there
Solution
Drop zone markup
The snippets below assume this minimal markup exists on the page — a drop zone that’s also keyboard-reachable, an error container announced to screen readers, and placeholders for progress bars and previews:
<div id="drop-zone" role="button" tabindex="0"
aria-label="Drop files here or press Enter to browse">
Drop files here or press Enter to browse
</div>
<div id="upload-errors" aria-live="polite"></div>
<div id="upload-list"></div>
<div id="preview-grid"></div>
#drop-zone {
border: 2px dashed #94a3b8;
border-radius: 8px;
padding: 2rem;
text-align: center;
cursor: pointer;
}
#drop-zone.drag-over {
border-color: #2563eb;
background: #eff6ff;
}
.upload-item { margin: 0.5rem 0; }
.progress-bar {
height: 8px;
background: #e5e7eb;
border-radius: 4px;
}
.progress-fill {
width: 0;
height: 100%;
background: #2563eb;
border-radius: 4px;
transition: width 0.2s;
}
The role="button" + tabindex="0" pair makes the zone focusable for keyboard users, and aria-live="polite" on the error container announces rejections without stealing focus.
Basic drop zone
const dropZone = document.getElementById("drop-zone");
dropZone.addEventListener("dragover", (e) => {
e.preventDefault();
dropZone.classList.add("drag-over");
});
dropZone.addEventListener("dragleave", () => {
dropZone.classList.remove("drag-over");
});
dropZone.addEventListener("drop", (e) => {
e.preventDefault();
dropZone.classList.remove("drag-over");
const files = Array.from(e.dataTransfer.files);
console.log(`Dropped ${files.length} files`);
files.forEach(file => {
console.log(`${file.name} — ${file.size} bytes — ${file.type}`);
});
});
Drop zone with file validation
Client-side checks are a UX filter, not security — pair them with server-side file upload validation or a renamed .exe will pass as image/png.
const MAX_SIZE = 5 * 1024 * 1024; // 5 MB
const ALLOWED_TYPES = ["image/jpeg", "image/png", "image/webp", "application/pdf"];
function setupDropZone(elementId) {
const dropZone = document.getElementById(elementId);
dropZone.addEventListener("dragover", (e) => {
e.preventDefault();
dropZone.classList.add("drag-over");
});
dropZone.addEventListener("dragleave", (e) => {
if (e.target === dropZone) {
dropZone.classList.remove("drag-over");
}
});
dropZone.addEventListener("drop", (e) => {
e.preventDefault();
dropZone.classList.remove("drag-over");
const files = Array.from(e.dataTransfer.files);
const valid = [];
const errors = [];
for (const file of files) {
if (!ALLOWED_TYPES.includes(file.type)) {
errors.push(`${file.name}: invalid type (${file.type})`);
continue;
}
if (file.size > MAX_SIZE) {
errors.push(`${file.name}: too large (${formatSize(file.size)})`);
continue;
}
valid.push(file);
}
errors.forEach(err => showError(err));
valid.forEach(file => uploadFile(file));
});
}
function formatSize(bytes) {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}
function showError(message) {
const errorDiv = document.getElementById("upload-errors");
errorDiv.innerHTML += `<p>${message}</p>`;
}
setupDropZone("drop-zone");
Upload with FormData and progress bar
The /api/upload endpoint must parse multipart form data — see Node.js file upload validation for the server side.
function uploadFile(file) {
const formData = new FormData();
formData.append("file", file);
const xhr = new XMLHttpRequest();
const progressBar = createProgressBar(file.name);
xhr.upload.addEventListener("progress", (e) => {
if (e.lengthComputable) {
const percent = Math.round((e.loaded / e.total) * 100);
progressBar.style.width = `${percent}%`;
progressBar.textContent = `${percent}%`;
}
});
xhr.addEventListener("load", () => {
if (xhr.status === 200) {
console.log(`${file.name} uploaded successfully`);
progressBar.parentElement.classList.add("upload-complete");
} else {
console.error(`${file.name} upload failed: ${xhr.status}`);
progressBar.parentElement.classList.add("upload-error");
}
});
xhr.addEventListener("error", () => {
console.error(`${file.name} upload error`);
progressBar.parentElement.classList.add("upload-error");
});
xhr.open("POST", "/api/upload");
xhr.send(formData);
return xhr;
}
function createProgressBar(fileName) {
const container = document.createElement("div");
container.className = "upload-item";
const label = document.createElement("span");
label.textContent = fileName;
const bar = document.createElement("div");
bar.className = "progress-bar";
const fill = document.createElement("div");
fill.className = "progress-fill";
bar.appendChild(fill);
container.appendChild(label);
container.appendChild(bar);
document.getElementById("upload-list").appendChild(container);
return fill;
}
Complete drag and drop uploader
class DragDropUploader {
constructor(elementId, options = {}) {
this.dropZone = document.getElementById(elementId);
this.maxSize = options.maxSize ?? 5 * 1024 * 1024;
this.allowedTypes = options.allowedTypes ?? ["image/jpeg", "image/png", "image/webp"];
this.uploadUrl = options.uploadUrl ?? "/api/upload";
this.onProgress = options.onProgress ?? (() => {});
this.onComplete = options.onComplete ?? (() => {});
this.onError = options.onError ?? (() => {});
this.setupEvents();
}
setupEvents() {
this.dropZone.addEventListener("dragover", (e) => {
e.preventDefault();
this.dropZone.classList.add("drag-over");
});
this.dropZone.addEventListener("dragleave", (e) => {
if (!this.dropZone.contains(e.relatedTarget)) {
this.dropZone.classList.remove("drag-over");
}
});
this.dropZone.addEventListener("drop", (e) => {
e.preventDefault();
this.dropZone.classList.remove("drag-over");
const files = Array.from(e.dataTransfer.files);
this.handleFiles(files);
});
// Also handle click to browse — keyboard included
this.dropZone.addEventListener("keydown", (e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
this.dropZone.click();
}
});
this.dropZone.addEventListener("click", () => {
const input = document.createElement("input");
input.type = "file";
input.multiple = true;
input.accept = this.allowedTypes.join(",");
input.addEventListener("change", () => {
this.handleFiles(Array.from(input.files));
});
input.click();
});
}
handleFiles(files) {
for (const file of files) {
const error = this.validate(file);
if (error) {
this.onError(file, error);
continue;
}
this.upload(file);
}
}
validate(file) {
if (!this.allowedTypes.includes(file.type)) {
return `Invalid type: ${file.type}`;
}
if (file.size > this.maxSize) {
return `File too large: ${this.formatSize(file.size)}`;
}
return null;
}
upload(file) {
const formData = new FormData();
formData.append("file", file);
const xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", (e) => {
if (e.lengthComputable) {
const percent = Math.round((e.loaded / e.total) * 100);
this.onProgress(file, percent);
}
});
xhr.addEventListener("load", () => {
if (xhr.status === 200) {
this.onComplete(file, JSON.parse(xhr.responseText));
} else {
this.onError(file, `Upload failed: ${xhr.status}`);
}
});
xhr.addEventListener("error", () => {
this.onError(file, "Network error");
});
xhr.open("POST", this.uploadUrl);
xhr.send(formData);
}
formatSize(bytes) {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}
}
// Usage
const uploader = new DragDropUploader("drop-zone", {
maxSize: 10 * 1024 * 1024,
allowedTypes: ["image/jpeg", "image/png", "image/webp", "application/pdf"],
uploadUrl: "/api/upload",
onProgress: (file, percent) => console.log(`${file.name}: ${percent}%`),
onComplete: (file, response) => console.log(`${file.name} done:`, response),
onError: (file, error) => console.error(`${file.name}: ${error}`)
});
Companion code: runnable upload demo — this class wired to a styled drop zone, progress bars and image previews, with a simulated mode that runs with no backend.
Image preview before upload
function previewImage(file) {
if (!file.type.startsWith("image/")) return;
const reader = new FileReader();
reader.onload = (e) => {
const img = document.createElement("img");
img.src = e.target.result;
img.style.maxWidth = "200px";
img.style.maxHeight = "200px";
img.style.borderRadius = "8px";
const container = document.createElement("div");
container.className = "preview-item";
container.appendChild(img);
const removeBtn = document.createElement("button");
removeBtn.textContent = "Remove";
removeBtn.onclick = () => container.remove();
container.appendChild(removeBtn);
document.getElementById("preview-grid").appendChild(container);
};
reader.readAsDataURL(file);
}
readAsDataURL keeps the whole file in memory as a base64 string — roughly 33% larger than the original. For large files prefer URL.createObjectURL(file), which yields a lightweight blob URL, and call URL.revokeObjectURL() when the preview is removed.
Filtering items and drop effect
A drop doesn’t only carry files — dataTransfer.items can hold dragged text or links too, so filter by kind === "file" before reading anything. While you’re at it, set e.dataTransfer.dropEffect inside dragover to control the cursor hint ("copy" shows the usual ”+” badge):
dropZone.addEventListener("dragover", (e) => {
e.preventDefault();
e.dataTransfer.dropEffect = "copy";
});
dropZone.addEventListener("drop", (e) => {
e.preventDefault();
const files = [];
for (const item of e.dataTransfer.items) {
if (item.kind === "file") files.push(item.getAsFile());
}
files.forEach(uploadFile);
});
Chromium-based browsers also expose item.getAsFileSystemHandle(), which returns a FileSystemFileHandle from the File System Access API — pick it when you need more than a one-shot read, like writing changes back to the same file. For reading dropped folders, webkitGetAsEntry() below remains the cross-browser path.
Reading dropped directories
The dataTransfer.files list stops at the top level — drop a folder and you won’t see what’s inside it. To walk the contents of a dropped folder, call webkitGetAsEntry() on each DataTransferItem; it works in all modern browsers — Chrome, Edge, Firefox and Safari:
dropZone.addEventListener("drop", (e) => {
e.preventDefault();
for (const item of e.dataTransfer.items) {
const entry = item.webkitGetAsEntry();
if (!entry) continue;
if (entry.isFile) {
entry.file(file => uploadFile(file));
} else if (entry.isDirectory) {
const reader = entry.createReader();
const readBatch = () => {
reader.readEntries(entries => {
if (entries.length === 0) return;
for (const child of entries) {
if (child.isFile) child.file(file => uploadFile(file));
}
readBatch(); // keep reading: readEntries returns max 100 per call
});
};
readBatch();
}
}
});
Queueing and canceling uploads
Firing one XHR per dropped file works until someone drops 50 of them — keep 2-4 in flight and park the rest in a queue. The map that tracks active requests gives you abort() for free when the user removes a file mid-upload:
const MAX_CONCURRENT = 3;
let inFlight = 0;
const queue = [];
const activeUploads = new Map(); // fileName -> XMLHttpRequest
function enqueueUpload(file) {
queue.push(file);
pumpQueue();
}
function pumpQueue() {
while (inFlight < MAX_CONCURRENT && queue.length > 0) {
const file = queue.shift();
inFlight++;
const xhr = uploadFile(file); // uploadFile returns the xhr
activeUploads.set(file.name, xhr);
}
}
// Inside uploadFile's load and error handlers, release the slot:
// inFlight--; activeUploads.delete(file.name); pumpQueue();
function cancelUpload(fileName) {
const xhr = activeUploads.get(fileName);
if (xhr) xhr.abort();
activeUploads.delete(fileName);
inFlight--;
pumpQueue();
}
Wire cancelUpload to the remove button in previewImage, and call enqueueUpload instead of uploadFile wherever you collect files.
Explanation
The HTML5 Drag and Drop API works through a series of events:
dragenterfires when a dragged item enters the drop zone — use it for visual feedback.dragoverfires continuously over the zone, and callinge.preventDefault()on it lets the drop through.dragleavefires when the item leaves the zone — time to remove the highlight. It also fires when the cursor moves over a child element, which is why naive handlers flicker.dropfires on release — calle.preventDefault()again, then pull the files out ofe.dataTransfer.files.
Key points:
preventDefault()ondragoveris the part everyone forgets. Without it the browser treats the drop as an “open this file” navigation instead of handing it to your handler.dataTransfer.filesholds the dropped files as aFileList; everyFileinside exposesname,size,typeandlastModified— the same object an<input type="file">gives you.- FormData + XHR for uploads:
FormDatapairs withfetchorXMLHttpRequestfor sending, but only XHR exposesuploadprogress events — that’s the one featurefetchstill doesn’t have. - FileReader handles reading contents in the page —
readAsDataURLproduces the base64 string behind image previews, andreadAsTextis what you want for plain text files. - Validate twice: check
file.typeandfile.sizeon the client for UX, then repeat the checks on the server.file.typecomes from the file extension and the OS, so it lies — a renamed.execan show up asimage/png. For real type checking, read the first bytes (magic numbers) of the file. - Cap concurrency: browsers happily upload in parallel, but firing 50 concurrent XHRs stalls the tab and the server. Queue uploads and keep 2-4 in flight at a time.
Variants
| Feature | Method | Use When |
|---|---|---|
| Basic drop | dataTransfer.files | Simple file selection |
| Validation | Check type + size | Production apps |
| Progress tracking | XMLHttpRequest upload | Large file uploads |
| Image preview | FileReader.readAsDataURL | Image uploaders |
| Click + drag | Hidden file input | Better UX |
| Folder drop | webkitGetAsEntry | Accepting directories |
| Drop cursor hint | dropEffect | Clearer drag feedback |
| File handles | getAsFileSystemHandle | Chromium, read+write access |
Best Practices
- Call
e.preventDefault()on bothdragoveranddrop— missing either one silently breaks the drop. - Validate type and size on the client for UX, then again on the server for security.
- Use
XMLHttpRequestwhen you need progress events;fetchis fine for small files where progress doesn’t matter. - Give visual feedback while dragging — a border, a highlight or an icon telling the user “drop it here”.
- Always pair drag-and-drop with a click-to-browse fallback; on mobile it’s often the only path that works.
- Make the zone keyboard-reachable (
role="button",tabindex="0", Enter/Space to browse) and putaria-live="polite"on the error list so screen readers announce rejections. - Show a progress bar for anything above ~1 MB so users don’t think the page froze.
- Abort pending
XMLHttpRequestandFileReaderwork when the user removes a file mid-upload. - Surface server errors with a message the user can act on, not just a
console.error.
Common Mistakes
- Skipping
preventDefault()ondragover— the browser then opens the dropped file in a new tab instead of letting your code handle it. - Trusting
file.typealone — it comes from the extension, so it won’t stop someone dropping a renamed executable. - Reaching for
fetchwhen you need a progress bar; it lacks upload progress events. - Removing the highlight on the first
dragleave— the event fires over child elements too. Comparee.relatedTargetor track an enter/leave counter. - Appending files to
FormDatawith a field name the backend doesn’t expect. - Shipping drag-and-drop with no click fallback — plenty of users never think to drag a file onto a page.
Further Reading
Frequently Asked Questions
How do I prevent the browser from opening the file when dropped outside the drop zone?
Drop a file anywhere outside the zone and the browser will happily navigate to it. Guard against that with global handlers on window:
window.addEventListener("dragover", (e) => e.preventDefault());
window.addEventListener("drop", (e) => e.preventDefault());
That stops the browser from hijacking the page when the user misses the drop zone.
Can I use fetch instead of XMLHttpRequest for uploads?
You can — just know that fetch won't report upload progress. When the progress bar doesn't matter, this is all you need:
const formData = new FormData();
formData.append("file", file);
const response = await fetch("/api/upload", {
method: "POST",
body: formData
});
How do I handle drag-and-drop on mobile devices?
Drag and drop on mobile is limited at best, so always ship a click-to-browse fallback with a hidden <input type="file">. If you genuinely need touch-based dragging, you'd build it yourself on top of the Touch Events API.
How do I limit the number of files?
Check files.length in the drop handler:
if (files.length > MAX_FILES) {
showError(`Maximum ${MAX_FILES} files allowed`);
return;
}
Can users drop a whole folder?
Yes, but not through dataTransfer.files — it only exposes the folder's top-level files. Use webkitGetAsEntry() on each DataTransferItem and recurse into FileSystemDirectoryEntry objects, as shown in Reading dropped directories. Support is good in Chrome, Edge, Firefox and Safari, but always keep the file input fallback for browsers and devices where folder drop doesn't work.
Related Resources
File Upload Validation: Secure File Handling Guide
How to handle file uploads securely with size, type, and content validation.
RecipeNode.js File Upload Validation: Type, Size, and Content
Validate file uploads in Node.js with multer — size limits, MIME checks, magic bytes and virus scanning for Express APIs.
RecipeCompress and Decompress Files with ZIP, GZIP, and TAR
Create and extract ZIP, GZIP, and TAR archives in Python, Node.js, Java, and Bash, with streaming reads and safe-extraction patterns.
RecipeJavaScript Clipboard Copy and Paste
Copy and paste text, HTML, and images in JavaScript with the Clipboard API — secure-context rules, an execCommand fallback, and real browser quirks
RecipeJavaScript LocalStorage with TTL Expiration
Store data in browser localStorage with TTL expiration: expiry wrappers, lazy cleanup, quota handling, stale-while-revalidate and cross-tab sync
RecipeJavaScript Infinite Scroll Pagination
Implement scroll-based data loading in JavaScript with IntersectionObserver: sentinel detection, fetch, loading and error states, and clean teardown.