How to drag and drop a file into a dropzone in HTML5

We can find plenty of demo and tutorials about it on the web, but it took me a while to understand how to setup something easy and quick.

The purpose is to have a zone where we can drop a file from our computer.

You need:

  1. A zone where the file will be dropped (for example a <div></div>)
  2. A minimum of three events:
    • drop
    • dragover
    • dragleave

The three events attached to our dropzone must all call event.preventDefault() otherwise it won’t work as expected.

Then, you can apply a style to the dropzone based on dragover and dragleave, and read the property event.dataTransfer.files from drop to get the file.

See here the super simple example: https://codepen.io/Aymkdn/pen/oovXNY

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *

*