How To Implement File Upload With Drag And Drop In Vanilla Js

Emma Delaney
2 min readDec 22, 2023

--

I have already written about drag and drop API concepts.

Now I want to show you how I implemented it a simple drag and drop file format for uploading to a website I’m building.

Identifies an HTML element that users should drag their files into:

<div
class="dropzone"
ondragover=`dragOverHandler(event)`
ondragleave=`dragLeaveHandler(event)`
ondrop=`dropHandler(event)`
>
...
</div>

ondragover is triggered when users drag a file onto the item. We can use it to add some style, for example a dashed border.

ondragleave is the opposite when we leave the drop zone.

I used this JS to add a dragging_over class to the element and style it with CSS:

function dragOverHandler(event) {
event.preventDefault();
const dropzone = document.querySelector('#dropzone');
dropzone.classList.add('dragging_over');
}

function dragLeaveHandler(event) {
event.preventDefault();
const dropzone = document.querySelector('#dropzone');
dropzone.classList.remove('dragging_over');
}
#dropzone.dragging_over {
border: 2px dashed #fff;
background-color: #666;
}

ondrop is triggered when the file (or multiple files!) are dropped into the zone.

It is This is where the action happens.

I collect the files, make sure they are images (in this example I only want images) and PUBLIC the data to /api/upload:

async function dropHandler(event) {
event.preventDefault()

const endpoint = `/api/upload`

if (event.dataTransfer.items) {
const formData = new FormData()
formData.append('action', 'upload')

for (let item of event.dataTransfer.items) {
if (item.kind === 'file') {
const file = item.getAsFile()
if (file) {
//I only want images
if (!file.type.match('image.*')) {
alert('only images supported')
return
}
formData.append('files', file)
}
}
}

try {
const response = await fetch(endpoint, {
method: 'POST',
body: formData,
})

if (response.ok) {
console.log('File upload successful')
} else {
console.error('File upload failed', response)
}
} catch (error) {
console.error('Error uploading file', error)
}
}
}

How you handle this server page depends on your server.

With Astro, I recovered the data with:

const formData = await Astro.request.formData()

console.log(formData.getAll('files'))

Implementing drag-and-drop file uploading in core JavaScript improves the user experience and makes the process more intuitive. By following this tutorial you can easily integrate this functionality into your web applications. You can always customize the code to your specific needs and explore additional features like file type validation and progress tracking for a complete file uploading solution.

Similar Article : How To Implement File Upload With Drag And Drop In Vanilla JS

--

--

Emma Delaney
Emma Delaney

Written by Emma Delaney

Dubai Based Software Engineer & digital marketing manager Channel : https://bit.ly/3WLAAJZ | https://bit.ly/3wRL2pc

Responses (1)