Drag and Drop File Sharing: Build Your Own
In this article
This guide walks you through creating a drag-and-drop file sharing page from scratch using plain HTML, CSS, and JavaScript. You'll build a page where visitors can drag files onto a drop zone, see them listed, and upload them to a server. No frameworks or libraries are required—just a modern browser and a basic web server for testing.
What You'll Need
- A text editor (VS Code, Sublime, Atom, or even Notepad)
- A modern browser (Chrome, Firefox, Edge, Safari)
- Basic knowledge of HTML, CSS, and JavaScript
- A local web server (like Python's built-in server or VS Code's Live Server extension) to test file uploads
- A server-side script (e.g., PHP, Node.js, Python) to handle the uploaded files—this guide includes a simple PHP example
Step-by-Step
- Create the HTML structure. Start with a standard HTML5 document. Add a
<div>with anid="drop-zone"that will act as your drag target. Inside it, place a paragraph or icon as a visual prompt. Also add a<ul>withid="file-list"to display the selected files, and a hidden<input type="file" id="file-input" multiple>for fallback selection. - Style the drop zone with CSS. Make the drop zone visually distinct—give it a dashed border, padding, and a background color. Add a hover or drag-over state (e.g., change border color to blue) to give feedback. Use
:hoverand a class like.dragoverthat you'll toggle with JavaScript. - Prevent default browser behavior. Browsers open files when you drop them, so you must prevent that. In JavaScript, add event listeners for
dragoveranddropon the drop zone. In both handlers, callevent.preventDefault()to stop the browser from navigating to the file. - Handle the dragover event. When the user drags a file over the zone, add the
.dragoverclass to change the style. Also setevent.dataTransfer.dropEffect = 'copy'to show a copy cursor. - Handle the drop event. In the drop handler, get the files from
event.dataTransfer.files. This is aFileListobject. Convert it to an array usingArray.from()or a loop. Then call a function to process the files. - Display the file list. For each file, create a
<li>element and set its text to the file name and size (e.g.,file.name + ' (' + file.size + ' bytes)'). Append it to the#file-list. This gives the user visual confirmation of what they've dropped. - Add a click-to-browse fallback. Some users prefer clicking. Make the drop zone clickable—when clicked, trigger the hidden file input. Listen for the
clickevent on the drop zone and callfileInput.click(). Then, on the file input'schangeevent, process the selected files using the same function. - Implement the upload function. Create an
uploadFiles(files)function. UseFormDatato append each file:formData.append('files[]', file). Then usefetch()to POST the data to your server endpoint (e.g.,upload.php). Handle the response with.then()and.catch()to show success or error messages. - Create the server-side script. If using PHP, create an
upload.phpfile that moves the uploaded files from the temporary location to a permanent folder. Use$_FILES['files']to access the array of files, loop through them, and usemove_uploaded_file()to save them. Return a JSON response indicating success or failure. - Test thoroughly. Run your local server and test with various file types and sizes. Test drag-and-drop and click-to-browse. Check the network tab in DevTools to ensure the POST request is sent correctly.
Common Mistakes
- Forgetting to preventDefault on dragover. Without this, the drop event will never fire because the browser will cancel the drag.
- Not handling the drop event on the correct element. Make sure the drop listener is on the drop zone, not the whole document.
- Using
event.dataTransfer.filesinstead ofevent.target.files. In the drop event, files are indataTransfer, not in the input'starget. - Not resetting the file input value. If you use the same input for multiple uploads, you need to set
input.value = ''after processing, otherwise the same file won't trigger the change event again. - Ignoring server-side validation. Always validate file types and sizes on the server to prevent security issues.
Tips
- Add a progress bar using
XMLHttpRequestinstead offetchfor better upload progress feedback. - Use
acceptattribute on the file input to filter file types (e.g.,accept="image/*"). - Drag-and-drop works on mobile? Not really. Always provide a fallback like a button.
- Use
Array.prototype.forEachorfor...ofto iterate over the FileList, as it's not a true array. - Style the drop zone with a dashed border and a hover effect to make it obvious it's interactive.
- Consider using
multipleattribute on the input to allow multiple files.
Troubleshooting
- Drop event not firing: Make sure you preventDefault on dragover, and that the drop listener is attached to the element that has the dragover listener.
- Files not uploading: Check the server endpoint URL in the fetch call. Ensure the server script is in the correct directory and permissions are set for the upload folder.
- Large files fail: Increase the
upload_max_filesizeandpost_max_sizein your PHP configuration. On the client side, you can also check file size before uploading. - Drag and drop works in Chrome but not Firefox: Firefox requires
event.dataTransfer.dropEffect = 'copy'to be set in the dragover handler. Ensure you're setting it. - File list doesn't update: If you're using the same input multiple times, clear its value with
input.value = ''after each upload.
Frequently Asked Questions
Can I use this without a server?
Yes, you can test the drag-and-drop interface locally without a server. The upload will fail, but the UI works. For full functionality, you need a server-side script to handle the files.
How do I limit file types?
You can set the accept attribute on the file input and also check the file type in JavaScript using file.type. For example, to only allow images, check file.type.startsWith('image/').
How do I handle multiple files?
The multiple attribute on the input and the drop event both support multiple files. Loop through the FileList and append each to FormData.
Is it possible to show upload progress?
Yes, use XMLHttpRequest instead of fetch. Listen to the upload.onprogress event to get the percentage and update a progress bar.
Can I drag and drop folders?
Yes, but it requires more complex handling. Use DataTransferItem.webkitGetAsEntry() to traverse the folder structure. This is not supported in all browsers, so test carefully.
How do I make the drop zone accessible?
Add role="button", tabindex="0", and handle the keydown event (e.g., Enter or Space) to trigger the file input. Also provide a visible label or text that explains the action.