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
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.
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].
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With