Search code examples
javaselenium-webdriverbambooawtrobotheadless-browser

How to upload the file into web browser through window popup in headless browser in automation (selenium webdriver)


I need to upload text file into my web page (By Clicking on Browse) through Window popup in selenium.

I have used below robot class to do this.

public void uploadFileUsingRobot(String filePath) throws AWTException,Exception{

          StringSelection path = new StringSelection(filePath);
          Toolkit.getDefaultToolkit().getSystemClipboard().setContents(path, null);

              Robot r = new Robot();

              r.keyPress(KeyEvent.VK_ENTER);
              r.keyRelease(KeyEvent.VK_ENTER);

              r.keyPress(KeyEvent.VK_CONTROL);    
              r.keyPress(KeyEvent.VK_V);

              r.keyRelease(KeyEvent.VK_V);    
              r.keyRelease(KeyEvent.VK_CONTROL);

              r.keyPress(KeyEvent.VK_ENTER);
              r.keyRelease(KeyEvent.VK_ENTER);

       }

It's working good in my local. But when i run this through bamboo plan, it's not working as bamboo running the code in headless browser.

Can anyone suggest me how can i upload the file in headless browser


Solution

  • When you execute your code on bamboo you probably use remote driver. To upload file you can set filepath with sendKeys to file input field and use fileDetector.

    Solution:

    If you have file input field

    <input id="fileinputfield" type="file">
    

    then following code will set filepath

    remoteWebDriver.setFileDetector(new LocalFileDetector());
    WebElement input = remoteWebDriver.findElement(By.id("fileinputfield"));
    input.sendKeys(filePath);
    

    Here you have an article describing solution.

    Possible problems you may reach:

    1. Getting remoteWebDriver. Here is one way you can try

      RemoteWebDriver remoteWebDriver = (RemoteWebDriver) ((WebDriverFacade) getDriver()).getProxiedDriver();
      
    2. Hidden (not displayed) file input field. If html is:

      <input id="fileinputfield" style="display:none;" type="file">
      

      Then you need to display it for time of executing code setting file path:

      JavascriptExecutor js = (JavascriptExecutor) getDriver();
      js.executeScript("document.getElementById('filedata').style.display='inline-block';");
      
      // RemoteWebDriver remoteWebDriver = (RemoteWebDriver) ((WebDriverFacade) getDriver()).getProxiedDriver();
      // remoteWebDriver.setFileDetector(new LocalFileDetector());
      // WebElement input = remoteWebDriver.findElement(By.id("fileinputfield"));
      // input.sendKeys(filePath);
      
      js.executeScript("document.getElementById('filedata').style.display='none';");