How to file Upload using Robot Class in Selenium Webdriver
We have
discussed uploading a file using using Webdriver Sendkeys method and Using
AutoIT Tool. Now here we will look into another way of doing file upload using
Robot class and String Selection 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";
@Test
public void testUpload() throws
InterruptedException
{
WebDriver driver = new FirefoxDriver();
driver.get(URL);
WebElement
element = driver.findElement(By.name("uploadfile"));
element.click();
uploadFile("path
to the file");
Thread.sleep(2000);
}
/**
* 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
setClipboardData(fileLocation);
//native key strokes for CTRL, V
and ENTER keys
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);
} catch (Exception exp) {
exp.printStackTrace();
}
}
}
Comments
Post a Comment