πŸ’‘ If you like this website, please share it with your friends and network! πŸš€
Back to All Scenarios
Scenario 63 of 100
Element Interaction
Advanced

Automating File Upload by Drag and Drop

🫳Scenario Overview

Automating File Upload by Drag and Drop

Key Takeaways & Cheat Sheet

  • βœ“Understand that Selenium Actions class cannot drag desktop files to browser targets
  • βœ“Locate hidden input type="file" elements behind drag-and-drop overlays
  • βœ“Send local file paths directly to inputs using standard sendKeys()
  • βœ“Use custom JS simulation scripts if input elements are not available in DOM

Short Direct Answer

Selenium cannot interact with OS windows to drag-and-drop local files. Instead, bypass the visual drop-zone. Find the hidden `<input type="file">` associated with the upload, use `sendKeys` to send the absolute local path to it, or run a custom JavaScript helper that simulates the drop-event directly on the container.

⚠️ Senior Warning (Red Flag)

Never attempt to drag a file from your operating system files to the browser window using Actions class. Selenium has no access to the OS file manager window.

πŸ’‘ STAR Deep Dive Explanation & Pro Tip

Most drag-and-drop interfaces are built on top of standard file inputs. Targeting the underlying input is highly reliable and avoids custom JS scripts.

SeleniumAutomation.java
Selenium 4 + Java
// βœ… Strategy 1: Target hidden input underneath drag-and-drop container
WebElement uploadInput = driver.findElement(By.cssSelector("input[type='file']"));
uploadInput.sendKeys("C:\docs\resume.pdf");

// βœ… Strategy 2: Custom JavaScript drag event dispatcher (Advanced dynamic grids)
WebElement dropZone = driver.findElement(By.className("dropzone-area"));
String dropScript = "var target = arguments[0];"
    + "var input = document.createElement('input');"
    + "input.type = 'file';"
    + "input.style.display = 'none';"
    + "input.onchange = function () {"
    + "  var rect = target.getBoundingClientRect();"
    + "  var e = { dataTransfer: { files: this.files } };"
    + "  target.oncustomdrop(e);" // Trigger site custom upload callback
    + "};"
    + "document.body.appendChild(input);"
    + "return input;";
WebElement tempInput = (WebElement) ((JavascriptExecutor) driver).executeScript(dropScript, dropZone);
tempInput.sendKeys("C:\docs\resume.pdf");