Last Updated On
In this tutorial, will see how to upload a document in Selenium.
We often face the problem where we have to upload a file in Web Application. This can be easily achieved in Selenium. We are using sendKeys() method to set the value of the file to upload.

Implementation
Setting up WebDriver:
This includes setting the browser for ChromeDriver and navigate to the web page that contains the upload button.
ChromeOptions options = new ChromeOptions();
WebDriver driver = new ChromeDriver(options);
driver.manage().window().maximize();
driver.get("https://demoqa.com/upload-download");
Locating the File Input Element:
Locate the download link using XPath and click on it to start the download.
WebElement upload = driver.findElement(By.id("uploadFile"));
Sending the File Path:
The absolute path of the file is sent to the file input element using the sendKeys() method, which effectively uploads the file to the form.
//Upload the file
upload.sendKeys("C:\\Users\\Vibha\\Documents\\SeleniumTest.txt");
Verify the message
Make sure that the file is uploaded successfully.
Close the browser
At the end of the program, quit the browser to free up the browser.
Below is an example of uploading a document in the Selenium.
public class Upload_Demo {
public static void main(String[] args) {
ChromeOptions options = new ChromeOptions();
WebDriver driver = new ChromeDriver(options);
driver.manage().window().maximize();
driver.get("https://demoqa.com/upload-download");
// Locating upload button
WebElement upload = driver.findElement(By.id("uploadFile"));
//Upload the file
upload.sendKeys("C:\\Users\\Vibha\\Documents\\SeleniumTest.txt");
String Message = driver.findElement(By.id("uploadedFilePath")).getText();
System.out.println("Message is :" + Message);
// close the browser
driver.close();
}
}
The web page after uploading the file looks something like as shown below

Common Issues we can encounter during uploading of the document:
- File Path – Use double backslashes (`\\`) in Windows file paths, or single slashes (`/`) in Unix-like systems.
- Element not found – Make sure correct locators is used to identify the upload button.
That’s it! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!
