12

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>");
12
  • It's not supposed to open the file chooser window. Commented Sep 15, 2017 at 13:31
  • 1
    Possible duplicate of How to upload file using Selenium WebDriver in Java Commented Sep 15, 2017 at 13:33
  • @JeffC : It is not a duplicate, because type of field is different and that solution isn't works in this case. Commented Sep 15, 2017 at 20:07
  • 1
    Input type is not file??then what type u want to upload Commented Sep 16, 2017 at 5:23
  • 1
    Can't help without getting complete page Commented Oct 24, 2017 at 18:46

2 Answers 2

5
+50

Upload a file using Java Selenium: sendKeys() or Robot Class.

This method is to Set the specified file-path to the ClipBoard.

  1. Copy data to ClipBoard as.

public static void setClipboardData(String filePath) {
    StringSelection stringSelection = new StringSelection( filePath );
    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
}

  1. Locate the file on Finder Window and press OK to select the file.
    • WIN [ Ctrl + V ]
    • MAC
      • "Go To Folder" - Command ⌘ + Shift + G.
      • Paste - Command ⌘ + V and
      • press OK to open it.

enum Action {
    WIN, MAC, LINUX, SEND_KEYS;
}
public static boolean FileUpload(String locator, String filePath, Action type) {
    WebDriverWait explicitWait = new WebDriverWait(driver, 10);

    WebElement element = explicitWait.until(ExpectedConditions.elementToBeClickable( By.xpath(locator) ));
    if( type == Action.SEND_KEYS ) {
        element.sendKeys( filePath );
        return true;
    } else {
        try {
            element.click();

            Thread.sleep( 1000 * 5 );

            setClipboardData(filePath);

            Robot robot = new Robot();
            if( type == Action.MAC ) { // Apple's Unix-based operating system.

                // “Go To Folder” on Mac - Hit Command+Shift+G on a Finder window.
                robot.keyPress(KeyEvent.VK_META);
                robot.keyPress(KeyEvent.VK_SHIFT);
                robot.keyPress(KeyEvent.VK_G);
                robot.keyRelease(KeyEvent.VK_G);
                robot.keyRelease(KeyEvent.VK_SHIFT);
                robot.keyRelease(KeyEvent.VK_META);

                // Paste the clipBoard content - Command ⌘ + V.
                robot.keyPress(KeyEvent.VK_META);
                robot.keyPress(KeyEvent.VK_V);
                robot.keyRelease(KeyEvent.VK_V);
                robot.keyRelease(KeyEvent.VK_META);

                // Press Enter (GO - To bring up the file.)
                robot.keyPress(KeyEvent.VK_ENTER);
                robot.keyRelease(KeyEvent.VK_ENTER);
                return true;
            } else if ( type == Action.WIN || type == Action.LINUX ) { // Ctrl + V to paste the content.

                robot.keyPress(KeyEvent.VK_CONTROL);
                robot.keyPress(KeyEvent.VK_V);
                robot.keyRelease(KeyEvent.VK_V);
                robot.keyRelease(KeyEvent.VK_CONTROL);
            }

            robot.delay( 1000 * 4 );

            robot.keyPress(KeyEvent.VK_ENTER);
            robot.keyRelease(KeyEvent.VK_ENTER);
            return true;
        } catch (AWTException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    return false;
}

File Upload Test :- You can find fileUploadBytes.html file by clicking on Try it Yourself.

public static void uploadTest( RemoteWebDriver driver ) throws Exception {
    //driver.setFileDetector(new LocalFileDetector());
    String baseUrl = "file:///D:/fileUploadBytes.html";
    driver.get( baseUrl );
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

    FileUpload("//input[1]", "D:\\log.txt", Action.SEND_KEYS);

    Thread.sleep( 1000 * 10 );

    FileUpload("//input[1]", "D:\\DB_SQL.txt", Action.WIN);

    Thread.sleep( 1000 * 10 );

    driver.quit();
}

For more information see my post.

Sign up to request clarification or add additional context in comments.

Comments

2

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");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.