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. In this tutorial, will see how to upload a document in Selenium.

Let’s explain this with the help of an example.
1) Launch new Browser and open “https://demoqa.com/upload-download”
2) Locate the button “Choose File” by using xpath
3) Use sendkeys() to upload the file
4) After uploading the file, verify the message displayed on web page
5) Close the browser
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class UploadDemo {
public static void main(String args[]) {
System.setProperty("webdriver.chrome.driver", "src\\test\\resources\\webdrivers\\window\\chromedriver.exe");
// Initiate Chrome browser
WebDriver driver = new ChromeDriver();
driver.get("https://demoqa.com/upload-download");
// Maximize the browser
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
// Locating upload button
WebElement upload = driver.findElement(By.id("uploadFile"));
//Upload the file
upload.sendKeys("C:\\Users\\Vibha\\Desktop\\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
