30. File Uploads via sendKeys & Download Validation

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'>:
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

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

Task

  • Implement uploadFileDirectly:
  • 1. Accept WebElement fileInput and String absolutePath.
  • 2. Call fileInput.sendKeys(absolutePath).
πŸ’‘Common doubts
Did you like the problem?
Lesson 30 of 44
Java
Loading code editor…
Next