</>

Technology

Selenium

Difficulty

Intermediate

Interview Question

How do you handle file upload and download in Selenium?

Answer

File Upload and Download in Selenium

File Upload

Method 1 — sendKeys() on input[type=file] (Most Reliable)

Java
// Works when there is a visible or hidden <input type="file">
WebElement uploadInput = driver.findElement(By.cssSelector("input[type='file']"));
uploadInput.sendKeys("C:\\Users\\user\\Downloads\\test-document.pdf");
// Or for Linux/Mac: "/home/user/test-document.pdf"

// For hidden file inputs (display:none) — still works!
// Selenium can sendKeys to hidden file inputs
WebElement hiddenInput = driver.findElement(By.id("file-upload"));
hiddenInput.sendKeys("/path/to/file.txt");

// If JavaScript is needed to unhide the input first:
js.executeScript("arguments[0].style.display='block';", hiddenInput);
hiddenInput.sendKeys("/path/to/file.txt");

Method 2 — Robot Class (System File Dialog)

Java
// When you MUST interact with OS file dialog (not recommended)
driver.findElement(By.id("upload-btn")).click();

// Small sleep to let dialog open
Thread.sleep(1000);

// Type the path using Robot (keyboard simulation)
Robot robot = new Robot();
StringSelection selection = new StringSelection("/path/to/file.txt");
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection, null);
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);

Multiple File Upload

Java
// Upload multiple files in one input
WebElement multiUpload = driver.findElement(By.id("multi-file-input"));
String files = "C:\\file1.txt" + "\n" + "C:\\file2.txt" + "\n" + "C:\\file3.txt";
multiUpload.sendKeys(files);

File Download

Configure ChromeOptions Download Directory

Java
// Set download path before launching Chrome
String downloadPath = System.getProperty("user.dir") + "/downloads";
new File(downloadPath).mkdirs();

Map<String, Object> prefs = new HashMap<>();
prefs.put("download.default_directory", downloadPath);
prefs.put("download.prompt_for_download", false);        // no save dialog
prefs.put("download.directory_upgrade", true);
prefs.put("safebrowsing.enabled", true);                 // allow downloads

ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("prefs", prefs);

WebDriver driver = new ChromeDriver(options);

Verify Downloaded File

Java
// Wait for file to appear (download takes time)
public boolean waitForDownload(String fileName, int timeoutSeconds) throws InterruptedException {
    String downloadPath = System.getProperty("user.dir") + "/downloads/";
    File expectedFile = new File(downloadPath + fileName);

    int elapsed = 0;
    while (elapsed < timeoutSeconds) {
        if (expectedFile.exists() && expectedFile.length() > 0) {
            System.out.println("Downloaded: " + expectedFile.getAbsolutePath());
            return true;
        }
        Thread.sleep(1000);
        elapsed++;
    }
    return false;
}

// Usage in test
driver.findElement(By.id("download-report")).click();
boolean downloaded = waitForDownload("report.pdf", 30);
Assert.assertTrue(downloaded, "Report PDF was not downloaded within 30s");

For Headless Chrome (Grid / CI)

Java
// Headless Chrome needs extra setting for downloads
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless=new", "--no-sandbox", "--disable-dev-shm-usage");
options.addArguments("--disable-gpu");

// Enable downloads in headless mode via CDP
ChromeDriver driver = new ChromeDriver(options);
DevTools devTools = driver.getDevTools();
devTools.createSession();
devTools.send(Browser.setDownloadBehavior(
    Browser.SetDownloadBehaviorBehavior.ALLOW,
    Optional.empty(),
    Optional.of("/tmp/downloads"),
    Optional.of(true)));

Clean Up After Test

Java
@AfterMethod
public void cleanupDownloads() {
    File dir = new File(System.getProperty("user.dir") + "/downloads");
    if (dir.exists()) {
        for (File f : Objects.requireNonNull(dir.listFiles())) {
            f.delete();
        }
    }
}

Follow AutomateQA

Related Topics