Search code examples
javaselenium-webdriverselenium-server

Handle file upload with Selenium Server Standalone


I try to execute testsuite on a remote host with use of Selenium Standalone Server. It should upload a file. I use code below to handle file uploads:

FileBrowserDialogHandler fileBrowserDialogHandler = new FileBrowserDialogHandler();
fileBrowserDialogHandler.fileUploadDialog(fileSource);

It doesn't work when I execute it remotely, because it is not able to open file chooser window. Input field looks like this on webpage:

<input type="text" id="file-path">

I replaced current solution with WebElement based one to avoid graphical window, but it doesn't work.

WebElement fileInput = driver.findElement(By.id("filepathelement"));
fileInput.sendKeys(filepath);

Input type is not file, so code below is not working:

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

Solution

  • The file(s) in question should be available on the machine (be it local or remote server) that your program is running on, for example, in your /resources directory

    On your local machine, this should work.

    chooseFileElement.waitForVisible().type("/file/path/filename.jpg");
    clickButton("Attach File");
    

    On Remote Server however, you need to associate a new instance of LocalFileDetector to the <input type=file> element.

    LocalFileDetector detector = new LocalFileDetector();
    File localFile = detector.getLocalFile("/file/path/filename.jpg");
    RemoteWebElement input = (RemoteWebElement) myDriver().findElement(By.id("fileUpload"));
    input.setFileDetector(detector);
    input.sendKeys(localFile.getAbsolutePath());
    clickButton("Attach File");