</>

Technology

Selenium

Difficulty

Intermediate

Interview Question

How to do file upload in Selenium?

Answer

Method 1: sendKeys() — Best approach for HTML file inputs Works when the upload button is a native <input type="file"> element:

Java
WebElement uploadInput = driver.findElement(By.id("fileUpload"));
uploadInput.sendKeys("C:\\Users\\nagen\\Desktop\\document.pdf");

No need to click the button — just send the file path directly.

Method 2: Robot API — for OS-level file dialog
Java
// Click the upload button to open OS dialog
driver.findElement(By.id("uploadBtn")).click();

// Copy path to clipboard
StringSelection path = new StringSelection("C:\\files\\test.pdf");
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(path, null);

// Paste and confirm
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);

Method 3: AutoIT Compile an AutoIT script to .exe and run it from Selenium:

Java
Runtime.getRuntime().exec("C:\\scripts\\fileUpload.exe");

Method 4: Sikuli Use image-based recognition to click the upload button and type the path:

Java
Screen screen = new Screen();
screen.click("upload_dialog.png");
screen.type("C:\\files\\test.pdf");

Recommended priority:

  1. sendKeys() on <input type="file"> — simplest and most reliable
  2. Robot API — when sendKeys does not work
  3. AutoIT / Sikuli — for complex OS dialogs

Follow AutomateQA

Related Topics