Selenium + Java · Lesson 30 of 44

0/44 done

Module 30: File Handling

30. File Uploads via sendKeys & Download Validation

15 minlesson

Your task

Implement uploadFileDirectly:

  1. Accept WebElement fileInput and String absolutePath.
  2. Call fileInput.sendKeys(absolutePath).

Write it in the editor, then press Check answer (Ctrl + Enter).

File Upload via sendKeys

Never click the upload button directly with Selenium, as the OS file dialog cannot be controlled by WebDriver! Instead, pass the absolute path directly into the <input type='file'>:

java
import java.io.File;

File testFile = new File("test-data/report.pdf");
WebElement fileInput = driver.findElement(By.cssSelector("input[type='file']"));
fileInput.sendKeys(testFile.getAbsolutePath());

Download Verification in Java

java
File downloadDir = new File(System.getProperty("user.home") + "/Downloads");
File expectedFile = new File(downloadDir, "exported_data.csv");
// Poll until expectedFile.exists() returns true

Key Takeaways & Walkthrough Summary

Uploading documents and verifying downloaded reports is essential for enterprise web apps. In this lesson, you will upload files using sendKeys on file input elements and verify downloaded files on disk. Let's handle files!

Part of the Selenium + Java course (Selenium with Java). Practice this concept live in the Selenium Online Compiler or explore our free automation practice form.

Common Doubts & Lesson Q&A

What if the <input type='file'> is hidden (display:none)?

Use JavascriptExecutor to temporarily change its style: js.executeScript("arguments[0].style.display='block';", fileInput); then sendKeys.

Ready? Solve the task in the editor

Use Check answer to mark it complete. Hints are there if you need them.

Java
Skip