Home >Web Front-end >JS Tutorial >How to Programmatically Set a File Input's Value After a Drag-and-Drop?
How to Set File Input Value When Dropping File on Page?
When creating a file input control that allows both traditional file selection and drag-and-drop, it's important to ensure that the file input field reflects the dropped file correctly. However, setting the file input value via JavaScript has been restricted in the past due to security concerns.
Solution
Thankfully, modern browsers have addressed these security vulnerabilities, allowing us to programmatically adjust the input[type="file"]'s files property. This enables us to simulate the effect of dropping a file into the file input field.
Implementation Details
Example Code
Here's a JavaScript code snippet that demonstrates how to set the file input value when a file is dropped onto the page:
let target = document.documentElement; let body = document.body; let fileInput = document.querySelector('input'); // Configure drag and drop event listeners 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; });
With this code in place, you will be able to set the file input value, allowing seamless interaction between selecting files through the file input field or directly dropping them onto the designated area.
The above is the detailed content of How to Programmatically Set a File Input's Value After a Drag-and-Drop?. For more information, please follow other related articles on the PHP Chinese website!