Categories
JavaScript Answers

How to drag drop files into standard HTML file input with JavaScript?

Spread the love

To drag drop files into standard HTML file input with JavaScript, we add an element to drop the file and a file input.

For instance, we write

<div id="dropContainer" style="border: 1px solid black; height: 100px">
  Drop Here
</div>

<input type="file" id="fileInput" />

to add a div to let user drop files and a file input.

Then we write

const dropContainer = document.querySelector("#dropContainer");
const fileInput = document.querySelector("#fileInput");

dropContainer.ondragover = dropContainer.ondragenter = (evt) => {
  evt.preventDefault();
};

dropContainer.ondrop = (evt) => {
  fileInput.files = evt.dataTransfer.files;
  const dT = new DataTransfer();
  dT.items.add(evt.dataTransfer.files[0]);
  dT.items.add(evt.dataTransfer.files[3]);
  fileInput.files = dT.files;

  evt.preventDefault();
};

to select the div and the file input.

Then we set the dragenter and dragover event handlers of the dropContainer to a function that stops the default behavior.

And we set the ondrop property to a function that gets the dropped file with evt.dataTransfer.files and set that as the value of the file input files property.

We then create a DataTransfer object and add the files into the items object with items.add.

Then we get the files from the dT object with dT.files and set that as the value of the file input files property.

Then we call preventDefault to stop the default behavior.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *