- Given any Web page, we can upload a file using sendKeys method in Selenium WebDriver. Lets discuss this in detail.
Upload file using SendKeys method in Selenium WebDriver:
- Using SendKeys method is the easiest way of uploading a file using Selenium Web driver. This can be achieved using three simple steps:
Step 1 – Choose File Button :
- First of all, click on the “Choose File” button to choose the file we wish to upload from our system.
WebElement uploadElenment = driver.findElement(By.id( "Choosefile" )); |
- We have taken id as “ChooseFile” for this web element.
Step 2 – Select File using sendKeys:
- Now select the file you want to upload from your machine. Give the path of the file on our machine to send keys method.
uploadElenment.sendKeys( "C:\\xyz.txt" ); |
Step 3 – Upload FIle :
- After clicking on “Upload” button, file will load successfully.
driver.findElement(By.id( "UploadFile" )).click(); |
Program to upload a file using sendKeys method:
package TestCases; import java.io.IOException; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.annotations.Test; public class FileUpload { @Test public void FileUploadTest() throws IOException { // Instantiation of driver object to launch browser System.setProperty( "webdriver.chrome.driver" , "C:\\work\\chromedriver.exe" ); WebDriver driver = new ChromeDriver(); // Locating "Choose file" button WebElement uploadElenment = driver.findElement(By.id( "Choosefile" )); // Pass the path of the file we want to upload using Sendkeys method uploadElenment.sendKeys( "C:\\xyz.txt" ); // click on the "Upload button to upload file" driver.findElement(By.id( "UploadFile" )).click(); } } |