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

How to Programmatically Set File Input Values After Drag-and-Drop?

DDD
Release: 2024-12-03 13:03:12
Original
374 people have browsed it

How to Programmatically Set File Input Values After Drag-and-Drop?

Setting File Input Value on Page Drop

Background

You are working on a control that enables file selection and submission through dropping into a designated area. However, you notice that the file input remains empty until the form is manually submitted.

Solution: Setting File Object from JavaScript

Thankfully, modern browsers now allow programmatic setting of input files using the files property. Here's how you can implement it using data transfer:

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

target.addEventListener('drop', (e) => {
  e.preventDefault();
  fileInput.files = e.dataTransfer.files;
});
Copy after login

Alternative Method: FileList

You can also set the file input value from a FileList object:

let fileInput = document.querySelector('input');

fileInput.files = [file1, file2, ...];
Copy after login

Disclaimer

The ability to set input file values depends on data transfer or FileList objects being available. Legacy security risks associated with this feature have been addressed in modern browsers.

Example

A demonstration can be found in the provided code snippet below:


let fileInput = document.querySelector('input');</p><p>target.addEventListener('drop', (e) => {<br>  e.preventDefault();<br>  fileInput.files = e.dataTransfer.files;<br>});


The above is the detailed content of How to Programmatically Set File Input Values After 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template