File upload using Robots

We have discussed uploading a file using using Webdriver Sendkeys method and Using AutoIT Tool. Now here we will look into an other way of doing file upload using Robot class and StringSelection class in java.

Robot class is used to (generate native system input events) take the control of mouse and keyboard. Once you get the control, you can do any type of operation related to mouse and keyboard through with java code.

There are different methods which robot class uses. Here in the below example we have used 'keyPress' and 'keyRelease' methods.

keyPress - takes keyCode as Parameter and Presses here a given key.
keyrelease - takes keyCode as Parameterand Releases a given key

Both the above methods Throws - IllegalArgumentException, if keycode is not a valid key.

We have defined two methods in the below example along with the test which is used to upload a file.

package com.easy.upload;

import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;

public class UploadFileRobot {

	String URL = "application URL";
	public void testUpload() throws InterruptedException
		WebDriver  driver = new FirefoxDriver();
		WebElement element = driver.findElement("uploadfile"));;
		uploadFile("path to the file");
     * This method will set any parameter string to the system's clipboard.
	public static void setClipboardData(String string) {
		//StringSelection is a class that can be used for copy and paste operations.
		   StringSelection stringSelection = new StringSelection(string);
		   Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
	public static void uploadFile(String fileLocation) {
        try {
        	//Setting clipboard with file location
            //native key strokes for CTRL, V and ENTER keys
            Robot robot = new Robot();
        } catch (Exception exp) {
Selenium Tutorials: 



I am not able to upload the image using this method and others also. It gets stuck at image open page.

Add new comment

This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.