Home >Web Front-end >JS Tutorial >How Can I Automatically Populate an Input File's Value Using Drag and Drop?

How Can I Automatically Populate an Input File's Value Using Drag and Drop?

DDD
DDDOriginal
2024-11-29 17:38:10466browse

How Can I Automatically Populate an Input File's Value Using Drag and Drop?

How to Automatically Populate Input File Value When Dragging and Dropping on Page

Background:

For security reasons, it was previously not possible to programmatically set the value of input files using JavaScript. However, with advancements in browser technology, this has changed.

Solution:

Step 1: Enable File Drop

Add drag and drop event listeners to the desired container:

const target = document.getElementById("container");

target.addEventListener("dragover", (e) => {
  e.preventDefault();
  target.classList.add("dragging");
});

target.addEventListener("dragleave", () => {
  target.classList.remove("dragging");
});

Step 2: Assign File Value

Capture the FileList object from the dataTransfer event:

target.addEventListener("drop", (e) => {
  e.preventDefault();
  target.classList.remove("dragging");

  const files = e.dataTransfer.files;
  document.getElementById("file-input").files = files;
});

Replace "container" with the ID of the container element you want to enable drag and drop on, and "file-input" with the ID of the input file element.

Note:

This method works on modern browsers that support the specification.

The above is the detailed content of How Can I Automatically Populate an Input File's Value Using Drag and Drop?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn