File Upload using Selenium & Robot Class

Robot class is used to simulate native system input events. In simple terms, we can take control of keyboard and mouse events using this class.

In order to upload a file, we will be using following 2 functions of Robot Class :

  • keyPress()
  • keyRelease()

Let’s understand this by following scenario :

1. Open URL : https://fineuploader.com/demos.html
2. Click on Upload Files button.
3. Paste the file path into the windows popup and Hit Enter.

UploadFile

Script :

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;

public class SampleTests {

	@Test
	public void testUpload() throws AWTException, InterruptedException {
		WebDriver driver = new ChromeDriver();
		driver.manage().window().maximize();
		driver.get("https://fineuploader.com/demos.html");
		driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
		//Click on upload Files Button
		driver.findElement(By.xpath("//*[text()='Upload files']/..")).click();
		Thread.sleep(2000);
		uploadFile("D:\\testFile.png");
	}

	public void uploadFile(String filePath) throws AWTException {
		//copy content
		StringSelection stringSelectionObj= new StringSelection(filePath);
		Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelectionObj, null);
	
		//paste content by CTRL + V event
		Robot robot = new Robot();
		robot.keyPress(KeyEvent.VK_CONTROL);
		robot.keyPress(KeyEvent.VK_V);
		robot.keyRelease(KeyEvent.VK_V);
		robot.keyRelease(KeyEvent.VK_CONTROL);
		robot.keyPress(KeyEvent.VK_ENTER);
		robot.keyRelease(KeyEvent.VK_ENTER);
	}

}

If you really like the information provided above, please don’t forget to hit a like on Facebook Page, you can also leave a comment.

Leave a Reply

Your email address will not be published. Required fields are marked *