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:
On the drop event:
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; });
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!