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
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());
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);
Click on the button and use the below code. Notice the use of '\\' instead of '\' in the path name,it is important for the code to work..
WebElement file_input = driver.findElement(By.id("id_of_button"));
file_input.sendKeys("C:\\Selenium\\ImageUpload_FF.exe");