Upload file using selenium webdriver

In this tutorial, you are going to learn how to upload file using selenium webdriver.

In your project, you may encounter a situation where you need to upload files. To upload the file from system, sendKeys() method can be used.

Example:



package com;

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;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class UploadFile {

static WebDriver driver;
String username = “username@gmail.com”;
String password = “pwd”;
String file = “C:\\Users\\username\\Desktop\\whitescreen.png”;

@BeforeTest
public void setup() throws Exception {
// chrome standalone server
System.setProperty(“webdriver.chrome.driver”, “C:\\Users\\username\\Downloads\\chromedriver_win32\\chromedriver.exe”);
//System.setProperty(“webdriver.ie.driver”, “C:\\Users\\username\\Downloads\\IEDriverServer_x64_3.8.0\\IEDriverServer.exe”);

//System.setProperty(“webdriver.gecko.driver”, “C:\\Users\\username\\Downloads\\geckodriver-v0.19.1-win64\\geckodriver.exe”);

driver = new ChromeDriver();
String URL=”https://www.*********.com/”;
driver.get(URL);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
}


@Test
public void login() throws Exception {
WebElement signIn = driver.findElement(By.linkText(“Sign In”));
signIn.click();
Thread.sleep(5000);

WebElement uname = driver.findElement(By.id(“email”));
uname.sendKeys(username);

WebElement pwd = driver.findElement(By.id(“pass”));
pwd.sendKeys(password);
pwd.submit();

}

@Test
public void upload() throws Exception{
WebElement payments = driver.findElement(By.linkText(“Payments”));
payments.click();

WebElement poi = driver.findElement(By.linkText(“Pay Outstanding Invoices”));
poi.click();

WebElement selectFile = driver.findElement(By.id(“account_verify_doc”));
selectFile.sendKeys(file);

WebElement submit = driver.findElement(By.id(“confirm”));

Thread.sleep(2000);

if(submit.isDisplayed()){
System.out.println(“File has uploaded successfully.”);
}

}


@AfterTest
public void tearDown() {

driver.close();

}
}

Result:

File has uploaded successfully.
PASSED: login
PASSED: upload

 

Tags: upload file using selenium webdriver, selenium, selenium webdriver.