Skip to content

How to implement file upload with drag and drop with Alpine

I wrote about how to implement file upload with drag and drop in vanilla JS.

Now let me do the same with Alpine, which makes our code simpler.

Identify an HTML element you want people to drag their files to, and use the @dragover @dragleave to set a local dragover property to true when we’re hovering the element dragging some file, and to false when moving away.

This lets us add some style (in this example I use Tailwind CSS to change the cursor when hovering the element and its children):

<div
  x-data="{ dragover: false }"
	:class="{ '*:cursor-alias': dragover }"
  @dragover.prevent="dragover = true"
  @dragleave.prevent="dragover = false"
>
...
</div>

:class is an Alpine.js thing, we can add the class only when dragover is true.

.prevent on those events automatically calls preventDefault() on them, to avoid the browser from opening the file at full screen instead of triggering our drag and drop events.

Now you can add @drop event that is fired when we file is dropped on the element.

<div
  ...
  @drop.prevent="drop"
>
...
</div>

You define the drop function in JavaScript

That’s where the action happens.

In this example I gather the files dropped, check they’re images (I only want images in this example) then I append them all to a formData object:

function drop(event) {
  if (!event.dataTransfer.items) return

  const formData = new FormData()

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

  //...
}

Once I have the formData object I can do a fetch() request:

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)
}

Alternatively you can trigger a form submit programmatically using htmx via htmx.ajax(), but there is some trickery to upload files with this method, I’ll explain that in another post.

How to handle that server-side depends on your server.

With Astro I got the data using:

const formData = await Astro.request.formData()

console.log(formData.getAll('files'))
→ Get my JavaScript Beginner's Handbook

I wrote 17 books to help you become a better developer, download them all at $0 cost by joining my newsletter

  • C Handbook
  • Command Line Handbook
  • CSS Handbook
  • Express Handbook
  • Git Cheat Sheet
  • Go Handbook
  • HTML Handbook
  • JS Handbook
  • Laravel Handbook
  • Next.js Handbook
  • Node.js Handbook
  • PHP Handbook
  • Python Handbook
  • React Handbook
  • SQL Handbook
  • Svelte Handbook
  • Swift Handbook

JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025

Bootcamp 2025

Join the waiting list