πŸ’‘ If you like this website, please share it with your friends and network! πŸš€
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");