Sunday 29 October 2017

Uploading file with the help of Robot class in Selenium Automation

While implementing automation, we always come across with a situation where our code need to upload a file using our selenium code.

As we know Selenium is a Web Automation tool and which don't support windows automation. In order to upload a files, we have to perform some Windows based operations.

There are different ways to achieve this. One of the way is to take the support of Robot and StringSelection class.

Below simple code will help to perform file upload as part of Selenium Automation:

import java.awt.AWTException;
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.firefox.FirefoxDriver;

public class FileUpload {

public static void main(String[] args) throws InterruptedException, AWTException {

// TODO Auto-generated method stub
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("https://html.com/input-type-file/");

                // Absolute path of the file need to uploaded
String fileLocation = "C:\\Users\\testData.xlsx";

                // the code which helps us to perform Copy and Paste options from Clipboard
StringSelection stringSelection = new StringSelection(fileLocation);

Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
                driver.findElement(By.id("fileupload")).click();
// CTRL+V and ENTER keys are the keyboard events to achieve the Keyboard operations
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);

Thread.sleep(5000);
driver.quit();
}
}

No comments:

Post a Comment