I saw that lots of people have Problems uploading a file in a test Environment with Selenium WebDriver. I use the selenium WebDriver and java, and had the same problem. I finally have found a solution, so i will post it here hoping that it helps someone else.
When i need to upload a file in a test, i click with Webdriver in the button and wait for the window "Open" to pop. And then i copy the path to the file in the clipboard and then paste it in the "open" window and click "Enter". This is working because when the window "open" pops up, the focus is always in the "open" button.
You will need these classes and method:
import java.awt.Robot; import java.awt.event.KeyEvent; import java.awt.Toolkit; import java.awt.datatransfer.StringSelection; public static void setClipboardData(String string) { StringSelection stringSelection = new StringSelection(string); Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null); }
And that is what i do, just after opening the "open" window:
setClipboardData("C:\\path to file\\example.jpg"); //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);
And that´s it. It is working for me, i hope it works for some of you.
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].
Actually, there is an in-built technique for this, too. It should work in all browsers and operating systems.
Selenium 2 (WebDriver) Java example:
// assuming driver is a healthy WebDriver instance WebElement fileInput = driver.findElement(By.xpath("//input[@type='file']")); fileInput.sendKeys("C:/path/to/file.jpg");
The idea is to directly send the absolute path to the file to an element which you would usually click at to get the modal window - that is <input type='file' />
element.
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