Selenium File Upload Download
Most file upload buttons on websites use a standard HTML input tag with type="file". Selenium treats this input like a regular text field, sending the file path directly instead of clicking through a native operating system dialog box.
Diagram: File Upload Without A System Dialog
Native OS Upload Dialog (Selenium cannot control this)
X
Instead:
<input type="file"> <--- sendKeys(filePath)
|
v
File attached directly, no dialog needed
Uploading A File
WebElement uploadInput = driver.findElement(By.id("resume-upload"));
uploadInput.sendKeys("C:\\Users\\Student\\Documents\\resume.pdf");
This sends the full file path as text, and the browser attaches the file without opening any popup window.
Why Native Dialogs Fail With Selenium
Selenium controls only the browser, not the operating system. A native file picker dialog runs outside the browser process, making it invisible to WebDriver. Tools like AutoIT or Robot class exist for these rare cases, but sendKeys() on the file input avoids the problem entirely on well-built websites.
Handling File Downloads
Selenium cannot click a Save button inside a native browser download popup, similar to the upload dialog limitation. The solution configures the browser to download files automatically without asking, before the test even starts.
Configuring Chrome For Silent Downloads
Map<String, Object> prefs = new HashMap<>();
prefs.put("download.default_directory", "C:\\Users\\Student\\Downloads");
prefs.put("download.prompt_for_download", false);
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("prefs", prefs);
WebDriver driver = new ChromeDriver(options);
This sets a fixed download folder and disables the confirmation prompt, so any download starts and saves immediately.
Verifying A Downloaded File
File downloadedFile = new File("C:\\Users\\Student\\Downloads\\certificate.pdf");
boolean exists = downloadedFile.exists();
System.out.println("File downloaded: " + exists);
This checks if the expected file appears in the download folder after clicking a download link, confirming the download completed successfully.
Waiting For Download Completion
Large files take time to finish downloading. Checking file existence too early may find a partial file still in progress.
int attempts = 0;
while (!downloadedFile.exists() && attempts < 20) {
Thread.sleep(1000);
attempts++;
}
This loop checks repeatedly for up to twenty seconds, giving the download enough time to finish before the test moves forward.
Practical Example
A course completion page offers a certificate download button. A test script clicks the button, waits for the PDF to appear in the download folder, and confirms the file size is greater than zero bytes, proving the certificate downloaded correctly and was not corrupted.
