How to upload file using Selenium WebDriver in Java How to upload file using Selenium WebDriver in Java java java

How to upload file using Selenium WebDriver in Java


First make sure that the input element is visible

As stated by Mark Collin in the discussion here:

Don't click on the browse button, it will trigger an OS level dialogue box and effectively stop your test dead.

Instead you can use:

driver.findElement(By.id("myUploadElement")).sendKeys("<absolutePathToMyFile>");

myUploadElement is the id of that element (button in this case) and in sendKeys you have to specify the absolute path of the content you want to upload (Image,video etc). Selenium will do the rest for you.

Keep in mind that the upload will work only If the element you send a file should be in the form <input type="file">


driver.findElement(By.id("urid")).sendKeys("drive:\\path\\filename.extension");


This is what I use to upload the image through upload window:

    //open upload window    upload.click();    //put path to your image in a clipboard    StringSelection ss = new StringSelection("C:\\IMG_3827.JPG");    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);    //imitate mouse events like ENTER, CTRL+C, CTRL+V    Robot robot = new Robot();    robot.keyPress(KeyEvent.VK_ENTER);    robot.keyRelease(KeyEvent.VK_ENTER);    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);

done