Back to All Scenarios
Scenario 41 of 100
File Upload/Download
Advanced
Automating File Upload when Input is Hidden
πScenario Overview
Automating File Upload when Input is Hidden
Key Takeaways & Cheat Sheet
- βLocate the hidden input element in the page source tree
- βUse JavaScript Executor to modify element styling to display="block"
- βMake opacity and visibility visible to allow Selenium interaction
- βUse standard sendKeys() to send the file path to the revealed input
Short Direct Answer
Modern websites hide the real `<input type="file">` element behind stylized drag-and-drop divs. To upload files, you must use JavaScript to alter the input element's CSS style (setting `display="block"` and `visibility="visible"`), perform standard `sendKeys` with the absolute path, and optionally hide it again.
β οΈ Senior Warning (Red Flag)
Do not attempt sendKeys on a hidden input (style="display:none") without making it visible first. Selenium will throw an ElementNotInteractableException.
π‘ STAR Deep Dive Explanation & Pro Tip
Altering styling via JS is highly robust and avoids flakiness in single-page apps (SPAs) that use advanced custom drag-and-drop components.
SeleniumAutomation.java
Selenium 4 + Java// β
Locate hidden input element
WebElement hiddenInput = driver.findElement(By.cssSelector("input[type='file']"));
// β
Force input visibility via JavaScript Executor styling
((JavascriptExecutor) driver).executeScript(
"arguments[0].style.display='block'; arguments[0].style.visibility='visible'; arguments[0].style.opacity='1';",
hiddenInput
);
// β
Send local file path to the now-visible input
hiddenInput.sendKeys("C:\test-data\profile.png");