Home > Web Front-end > JS Tutorial > How to Programmatically Set File Input Value with Drag and Drop?

How to Programmatically Set File Input Value with Drag and Drop?

Linda Hamilton
Release: 2024-12-01 15:23:09
Original
219 people have browsed it

How to Programmatically Set File Input Value with Drag and Drop?

How to Set File Input Value When Dropping File on Page?

In an attempt to create a control where users can both manually select and drop files to submit a form, you've encountered an issue: the file input remains empty when files are dropped. While security concerns previously disallowed programmatically setting file input values, modern browsers have addressed these vulnerabilities.

The Solution: Utilize DataTransfer or FileList

You can now set file input values on modern browsers by utilizing the dataTransfer or FileList objects. Since December 2017, Firefox and other major browsers allow programmatic file input manipulation.

Method:

  1. Prevent default event behavior on dragover and dragleave events to enable file input interaction.
  2. On the drop event:

    • Set fileInput.files equal to the dropped files obtained from e.dataTransfer.files. This assigns the files dropped onto the page to the file input.
  3. Remove the visual cues indicating the user is dragging.

Example:

let target = document.documentElement;
let body = document.body;
let fileInput = document.querySelector('input');

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

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

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

  fileInput.files = e.dataTransfer.files;
});
Copy after login

Note: This method works on modern browsers and provides a secure way to handle file inputs with drag-and-drop functionality.

The above is the detailed content of How to Programmatically Set File Input Value with Drag and Drop?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template