File upload (sendKeys to input) in Selenium Java - Build an Automation Script
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import java.time.Duration; public class FileUploadTest { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); WebDriver driver = new ChromeDriver(); WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); try { driver.get("https://example.com/file-upload"); // Locate file input WebElement fileInput = wait.until(ExpectedConditions.elementToBeClickable(By.id("file-upload"))); // Set file path - adjust path as needed String filePath = "C:\\Users\\TestUser\\Documents\\sample.txt"; fileInput.sendKeys(filePath); // Click upload button WebElement uploadButton = driver.findElement(By.id("upload-button")); uploadButton.click(); // Wait for confirmation message WebElement successMessage = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("upload-success"))); // Assert message text if (!"Upload successful!".equals(successMessage.getText())) { throw new AssertionError("Upload confirmation text mismatch"); } System.out.println("Test passed: File uploaded successfully."); } catch (Exception e) { e.printStackTrace(); } finally { driver.quit(); } } }
This test script uses Selenium WebDriver with Java to automate the file upload process.
First, it opens the file upload page. Then it waits explicitly for the file input element to be clickable to ensure it is ready.
It uses sendKeys to input the full file path into the file input element. This simulates selecting a file from the local machine.
Next, it clicks the upload button to start the upload.
After clicking, it waits explicitly for the upload confirmation message to appear, ensuring the upload completed.
Finally, it asserts that the confirmation message text matches the expected success message.
Explicit waits and By.id locators are used for reliability. The file path is kept as a variable for easy changes.
Now add data-driven testing with 3 different file paths to upload different files