How to upload File in Selenium?
File upload in Selenium is very straightforward when dealing with standard HTML <input type=”file”> elements.
You simply send the file path to the input element using .sendKeys(). Selenium handles the rest (no need to interact with the OS dialog).
Sample Code:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class FileUploadExample {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");
WebDriver driver = new ChromeDriver();
try {
driver.get("https://demoqa.com/upload-download");
WebElement uploadInput = driver.findElement(By.id("uploadFile"));
// Give your absolute file path here
uploadInput.sendKeys("C:\\path\\to\\your\\file.txt");
// Optionally, verify upload
WebElement uploadedPath = driver.findElement(By.id("uploadedFilePath"));
System.out.println("Uploaded file path: " + uploadedPath.getText());
} finally {
driver.quit();
}
}
}
Key Points
- The file input must not be hidden. If it is, you may need to remove the ‘hidden’ attribute with JavaScript before sending keys.
- No need to click on the “Browse” button.
- Path must be absolute (not relative).
- Works on all platforms (Windows: C:\\file.txt, Mac/Linux: /Users/name/file.txt).