File Upload using Robot Class in Selenium

File Upload using Robot Class in Selenium will discuss about how we can upload a file into web application while automating the application using selenium webdriver. As we know that selenium webdriver automates only browsers (i.e. web applications only). But sometimes we might need to automate windows based applications/popups such as upload a file or download a file etc…

But selenium can not handle these kind of scenarios. So, we will use some third party tools to automate these type of functionality. Especially uploading a file is one of the scenarios we will face while automating most of the applications. For this we will depend mostly some third party tools like AutoIt and Sikuli.

But in this blog we will NOT look into Sikuli or AutoIt to automate file upload functionality in selenium webdriver.  Instead we will see one of the Java classes called Robot. Robot is a class in the AWT package of Java, by using this we can handle window based applications/popups. Now we use this provision to automate file upload functionality in selenium webdriver.

If you use some third-party tools, those are extra burden to the code or framework. And sometimes these are not compatible with the tools which we use to build the application.

So, we can use this Robot class to avoid those kind of scenarios. Basically Robot class will simulate the Keyboard and mouse actions. So, we can use the Robot class methods to handle these kind of scenarios.

Below is the sample code to handle the file upload in selenium webdriver using Robot Class:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

import java.awt.*;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;

public class FileUploadWithRobot
    public static void main(String args[]) throws Exception
        Robot robot = new Robot();
        WebDriver driver = new FirefoxDriver();



        StringSelection selection = new StringSelection("D:\\Selenium\\Clean.bat");






In the above program, 22,23 lines will copy the file path and hold in the clipboard. So, we can simulate the keyboard events to paste the same in the file name textbox as by default the control will be in the same location. If the focus is not there in that location then we need make sure that the cursor should be there in the file name textbox.

And keyPress and keyRelease methods are the method to simulate the keyboard press and release actions. So, Control + V will paste the clipboard content in the file name textbox. And Enter will simulate the Enter button in the keyboard. Then file will upload successfully in the application.

This way we can upload a file in selenium using Robot class.

Please watch the youtube video for better understanding.