We use file upload to test if a website accepts files correctly. Using sendKeys to input simulates choosing a file without clicking buttons.
0
0
File upload (sendKeys to input) in Selenium Java
Introduction
When testing a form that asks users to upload a profile picture.
When verifying if a document upload feature accepts the right file types.
When automating tests that require uploading files without manual interaction.
When checking if error messages appear for wrong file uploads.
When testing file upload limits like size or number of files.
Syntax
Selenium Java
WebElement uploadElement = driver.findElement(By.id("file-upload")); uploadElement.sendKeys("C:\\path\\to\\file.txt");
Use the absolute file path in sendKeys.
Locate the file input element directly, not the upload button.
Examples
Upload a PDF file using the input element found by its name attribute.
Selenium Java
driver.findElement(By.name("upload")).sendKeys("/Users/john/Documents/report.pdf");
Upload an image file using a CSS selector for the file input.
Selenium Java
WebElement input = driver.findElement(By.cssSelector("input[type='file']")); input.sendKeys("D:\\images\\photo.png");
Sample Program
This test opens a webpage with a file upload form, uploads a file by sending its path to the input, clicks submit, and checks if a success message appears.
Selenium Java
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class FileUploadTest { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); WebDriver driver = new ChromeDriver(); try { driver.get("https://example.com/upload"); WebElement uploadInput = driver.findElement(By.id("file-upload")); uploadInput.sendKeys("C:\\Users\\TestUser\\Documents\\testfile.txt"); WebElement submitButton = driver.findElement(By.id("submit-upload")); submitButton.click(); WebElement successMessage = driver.findElement(By.id("upload-success")); if (successMessage.isDisplayed()) { System.out.println("File uploaded successfully."); } else { System.out.println("Upload failed."); } } finally { driver.quit(); } } }
OutputSuccess
Important Notes
Make sure the file path is correct and accessible by the test machine.
Do not try to click the file input; sendKeys works directly on it.
File input elements must be visible or interactable for sendKeys to work.
Summary
Use sendKeys on the file input element to upload files in tests.
Always provide the full file path as a string.
Check for success messages or page changes after upload.