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

download all my books for free

  • javascript handbook
  • typescript handbook
  • css handbook
  • node.js handbook
  • astro handbook
  • html handbook
  • next.js pages router handbook
  • alpine.js handbook
  • htmx handbook
  • react handbook
  • sql handbook
  • git cheat sheet
  • laravel handbook
  • express handbook
  • swift handbook
  • go handbook
  • php handbook
  • python handbook
  • cli handbook
  • c handbook

subscribe to my newsletter to get them

Terms: by subscribing to the newsletter you agree the following terms and conditions and privacy policy. The aim of the newsletter is to keep you up to date about new tutorials, new book releases or courses organized by Flavio. If you wish to unsubscribe from the newsletter, you can click the unsubscribe link that's present at the bottom of each email, anytime. I will not communicate/spread/publish or otherwise give away your address. Your email address is the only personal information collected, and it's only collected for the primary purpose of keeping you informed through the newsletter. It's stored in a secure server based in the EU. You can contact Flavio by emailing [email protected]. These terms and conditions are governed by the laws in force in Italy and you unconditionally submit to the jurisdiction of the courts of Italy.

Related posts about js: