javaseleniumselenium-webdriverfile-uploadselenium-firefoxdriver

How to handle Firefox Upload File window with Selenium WebDriver - Java


I know this topic is a duplicate but , I have applied other solutions too , and as an outcome I have a problem about sending the correct key to correct place for File Upload window.

I have used this piece of code to Open and send keys to Upload File:

WebElement fileInput = driver.findElement(By.id("upload-resume-button"));
fileInput.sendKeys("C:/Users/EvrenosCareer/Desktop/filename.pdf");

By sending keys correct button gets activated and File Upload window opens as expected , but keys was send as something else , and it appears down left corner of the browser; not File upload window. Please check this link , 5 sec video to see exactly what I am talking about: https://evrenos-hotmail.tinytake.com/sf/MTcxNDY0N181Njg2OTY1


Solution

  • You can directly do fileInput.sendKeys("C:/Users/EvrenosCareer/Desktop/filename.pdf") if the type of the element is "file" else you will have to upload file using Robot class. You don't have to click on fileInput to send keys on that element.

    Upload file through Robot class:

     WebElement element = driver.findElement(By.id("upload-resume-button"));
     element.click();
    StringSelection stringSelection = new StringSelection("path to File");
    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
     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);