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; });
Alternative Method: FileList
You can also set the file input value from a FileList object:
let fileInput = document.querySelector('input'); fileInput.files = [file1, file2, ...];
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!