Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File Upload using Selenium WebDriver and Java Robot Class

I am using Selenium WebDriver and Java and I need to automate the file upload feature. I tried a lot, but the moment the Browse button is clicked and a new window opens the script stops executing further and rather getting stuck. I tried in both FireFox and IE driver but to no avail.

I tried also by calling an autoit exe file, but as the new window opens on click of Browse button, the particular statement

Runtime.getRuntime().exec("C:\\Selenium\\ImageUpload_FF.exe")

couldn't be exeuted. Kindly help

like image 854
Parikshit Avatar asked Apr 10 '11 06:04

Parikshit


People also ask

Can we use Robot class to upload file in Selenium Webdriver?

We can upload a file with Java Robot class in Selenium webdriver. It can produce simulationsfor the Keyboard and Mouse Event. It is derived from the AWT package.

Can we do file upload through Selenium?

We can upload files using Selenium Webdriver. This is achieved by the sendKeys method. We have to first identify the element which performs the file selection by mentioning the file path [to be uploaded].


2 Answers

This should work with Firefox, Chrome and IE drivers.

FirefoxDriver driver = new FirefoxDriver();

driver.get("http://localhost:8080/page");

File file = null;

try {
    file = new File(YourClass.class.getClassLoader().getResource("file.txt").toURI());
} catch (URISyntaxException e) {
    e.printStackTrace();
}

Assert.assertTrue(file.exists()); 

WebElement browseButton = driver.findElement(By.id("myfile"));
browseButton.sendKeys(file.getAbsolutePath());
like image 58
lisak Avatar answered Sep 28 '22 10:09

lisak


I think I need to add something to Alex's answer.

I tried to open the Open window by using this code:

driver.findElement(My element).click()

The window opened, but the driver became unresponsive and the actions in the code didn't even get to the Robot's actions. I do not know the reason why this happens, probably because the browser lost focus.

The way I made it work was by using the Actions selenium class:

 Actions builder = new Actions(driver);

 Action myAction = builder.click(driver.findElement(My Element))
       .release()
       .build();

    myAction.perform();

    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);
like image 21
vali83 Avatar answered Sep 28 '22 09:09

vali83