How to Upload File in Selenium using Robot Class

Profile picture for user devraj

The Robot class in the Java AWT package is used to generate native system input events where control of the mouse and keyboard is needed. 

Demo: Auto Pract Upload File Functionality at bottom of the page

Upload File in Selenium using Robot Class

Code to Click on Choose File Button

public void clickChooseFile()
{
    JavascriptExecutor js = (JavascriptExecutor)driver;

    WebElement element = driver.findElement(By.xpath("(//input[@class='form-control'])[3]"));
    driver.findElement(By.cssSelector("button.close")).click();
        
    js.executeScript("window.scrollTo(0, document.body.scrollHeight)");
    js.executeScript("arguments[0].click();", element);
}

Code to Upload File

@Test
public void shouldAnswerWithTrue() throws AWTException, InterruptedException
{
    //Click on Choose File Button
    clickChooseFile();
		
    //Path of file to be uploaded
    String filePath = System.getProperty("user.dir")+File.separator+"upload"+File.separator+"sample.csv";
        
    //Creates a transferable object capable of transferring the specified string in plain text format.
    StringSelection ss = new StringSelection(filePath);
		
    // Copy file path to clipboard
    // getSystemClipboard - gets the singleton instance of clipboard
    // Clipboard - class that implements a mechanism to transfer data using cut/copy/paste operations.
    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);

    Robot robot = new Robot();
//		robot.delay(2000);

    // Press and release CTRL+V to paste copied file path in textbox
    robot.keyPress(KeyEvent.VK_CONTROL);
    robot.keyPress(KeyEvent.VK_V);
    robot.keyRelease(KeyEvent.VK_V);
    robot.keyRelease(KeyEvent.VK_CONTROL);

//		robot.delay(2000);

    // Press Open button using Enter Key
    robot.keyPress(KeyEvent.VK_ENTER);
    robot.keyRelease(KeyEvent.VK_ENTER);
          
    // Wait for control to switch to web 
    Thread.sleep(1000);
		
    // Click on upload button
    driver.findElement(By.cssSelector("button.btn-success")).click();
}

Here you can uncomment robot delay to see the upload in action without it it will work very fast.