How to Handle File Upload Window in Selenium Webdriver Java

Selenium is an open-source web-based automation tool that is implemented using a web driver. We will be using geckodriver because Selenium 3 enables geckodriver as the default WebDriver implementation for Firefox.

Pre-requisites:

  1. geckodriver.exe
  2. maven dependency selenium
 <dependency>
    <groupid>org.seleniumhq.selenium</groupid>
	<artifactid>selenium-java</artifactid>  
	<version>4.1.1</version> 
 </dependency>

Steps:

The following 4 steps will automate the process:

  1. Set webdriver.gecko.driver and its' path as a system property.
  2. Set the firefox diver and browse to the website link.
  3. Get the file-upload web element; input using webdriver.findElement() function and css selector.
  4. Send the path of the file as a key. This will handle the window and the file will be uploaded successfully.

Let’s see all the above steps in the code. We will use webelement.sendkeys() function to give the file path to the input file web element.
import org.openqa.selenium.By;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

public class HandleFileUploadWindow {
    public static String GECKODRIVER_PATH = "F:\\WORK\\SeleniumShortTasks\\HandleFileUploadWindow\\src\\main\\resources\\geckodriver.exe";

    public static void main(String[] args) {
        //set firefox webdriver
        System.setProperty("webdriver.gecko.driver", GECKODRIVER_PATH);
        WebDriver driver = new FirefoxDriver();

        //get the firefox browser & Browse the Website for file sharing
        String sitelink = "https://filebin.net/";
        driver.get(sitelink);

        String filePath = "C:\\Users\\Momin-PC\\Pictures\\Polish_20210926_150306560~2.jpg";

        //Get the add file element
        WebElement addFile = driver.findElement(By.cssSelector("input.upload"));
        addFile.sendKeys(filePath);

    }

}

Output:


All resources used in this tutorial are attached:
  • source code
  • geckdriver.exe
Download

Comments