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

Spread the love

Sometimes, we want to drag-drop files into standard HTML file input and JavaScript.

In this article, we’ll look at how to drag-drop files into standard HTML file input and JavaScript.

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

To drag-drop files into standard HTML file input and JavaScript, we add a div to drop the files into.

For instance, we write

<!DOCTYPE html>
<html>
  <body>
    <div id="dropContainer" style="border: 1px solid black; height: 100px">
      Drop Here
    </div>
    Should update here:
    <input type="file" id="fileInput" />
  </body>
</html>

to add a div and a file input.

Then we write

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 stop the default behavior on the div with

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

Then we get the files on drop with dropContainer.ondrop.

We get the files with evt.dataTransfer.files.

We add the files intoi the DataTransfer with dT.items.add.

Then we put the files into the file input with fileInput.files = dT.files;.

Conclusion

To drag-drop files into standard HTML file input and JavaScript, we add a div to drop the files into.

Leave a Reply

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