</>

Technology

Scenario-Based

Difficulty

Intermediate

Interview Question

How do you test file upload in Selenium?

Answer

Testing File Upload in Selenium

File upload dialogs are OS-level windows that Selenium cannot interact with directly. But for standard HTML <input type="file"> elements, sendKeys() works perfectly.

Method 1 — sendKeys() on File Input (Most Common)

Java
// Locate the file input element (even if hidden)
WebElement fileInput = driver.findElement(By.cssSelector("input[type='file']"));

// Send the full absolute file path
fileInput.sendKeys("C:\\test-files\\sample.pdf");

// Or on Linux/Mac CI
fileInput.sendKeys("/home/runner/test-files/sample.pdf");

Handle Hidden File Input

Some file inputs have display:none. Use JavaScript to make it visible first:

Java
WebElement fileInput = driver.findElement(By.cssSelector("input[type='file']"));

// Remove display:none
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].style.display='block';", fileInput);

fileInput.sendKeys("C:\\test-files\\sample.png");

Verify File Was Selected

Java
// Check the file name appears on page after selection
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(5));
WebElement fileNameDisplay = wait.until(
    ExpectedConditions.visibilityOfElementLocated(By.cssSelector(".file-name"))
);
Assert.assertTrue(fileNameDisplay.getText().contains("sample.png"));

Cross-Platform Path Helper

Java
public String getTestFilePath(String fileName) {
    return System.getProperty("user.dir") +
           File.separator + "src" +
           File.separator + "test" +
           File.separator + "resources" +
           File.separator + fileName;
}

// Usage
fileInput.sendKeys(getTestFilePath("sample.pdf"));

What NOT to Do

  • Don't use AutoIt or Robot class for standard HTML file inputs — sendKeys() is sufficient and cross-platform
  • Don't click the button that opens the OS dialog — find the <input type="file"> directly
  • Don't use drag-and-drop simulation when sendKeys is simpler

When AutoIt/Robot IS Needed

Only when the upload is truly OS-native (no <input type="file"> in DOM) — rare in modern web apps.

Follow AutomateQA

Related Topics