File Upload using Selenium WebDriver and Java Robot Class
Asked Answered
R

8

17

I am using Selenium WebDriver and Java and I need to automate the file upload feature. I tried a lot, but the moment the Browse button is clicked and a new window opens the script stops executing further and rather getting stuck. I tried in both FireFox and IE driver but to no avail.

I tried also by calling an autoit exe file, but as the new window opens on click of Browse button, the particular statement

Runtime.getRuntime().exec("C:\\Selenium\\ImageUpload_FF.exe")

couldn't be exeuted. Kindly help

Rome answered 10/4, 2011 at 6:58 Comment(1)
take a look here: #9432478 , that worked for me fine!Overthecounter
A
23

This should work with Firefox, Chrome and IE drivers.

FirefoxDriver driver = new FirefoxDriver();

driver.get("http://localhost:8080/page");

File file = null;

try {
    file = new File(YourClass.class.getClassLoader().getResource("file.txt").toURI());
} catch (URISyntaxException e) {
    e.printStackTrace();
}

Assert.assertTrue(file.exists()); 

WebElement browseButton = driver.findElement(By.id("myfile"));
browseButton.sendKeys(file.getAbsolutePath());
Applied answered 25/5, 2011 at 21:0 Comment(1)
please update you post with details what 'browseButton' stands for. From the first sight it was not so obvious for me. Thanks in advance. upvote from me.Overthecounter
S
3

I think I need to add something to Alex's answer.

I tried to open the Open window by using this code:

driver.findElement(My element).click()

The window opened, but the driver became unresponsive and the actions in the code didn't even get to the Robot's actions. I do not know the reason why this happens, probably because the browser lost focus.

The way I made it work was by using the Actions selenium class:

 Actions builder = new Actions(driver);

 Action myAction = builder.click(driver.findElement(My Element))
       .release()
       .build();

    myAction.perform();

    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);
Surf answered 26/7, 2012 at 8:51 Comment(0)
C
3

Click on the button and use the below code. Notice the use of '\\' instead of '\' in the path name,it is important for the code to work..

WebElement file_input = driver.findElement(By.id("id_of_button"));
file_input.sendKeys("C:\\Selenium\\ImageUpload_FF.exe");
Cahra answered 1/12, 2013 at 8:30 Comment(0)
L
0

I also use the selenium webdriver and java, and had the same problem. What i do is copying the path to the file in the clipboard and then paste it in the "open" window and click "Enter". This is working because the focus is always in the "open" button.

Here is the code:

You will need these classes and method:

import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;


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

And that is what i do, just after opening the "open" window:

setClipboardData("C:\\path to file\\example.jpg");
//native key strokes for CTRL, V and ENTER keys
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);

And that´s it. It is working for me, i hope it works for some of you.

Lindseylindsley answered 24/2, 2012 at 13:48 Comment(0)
E
0

The moment after the modal dialog opens the script will not work, it just hangs. So call autoit.exe first and then click to open the modal dialog.

It works fine like this,

 Runtime.getRuntime().exec("Upload_IE.exe");
 selenium.click("//input[@name='filecontent']");
Emotion answered 4/7, 2012 at 6:42 Comment(0)
D
0

By using RemoteWebElement class you can Upload the file using the following code.

// TEST URL: "https://www.filehosting.org/"
// LOCATOR: "//input[@name='upload_file'][@type='file'][1]"

LocalFileDetector detector = new LocalFileDetector();
File localFile = detector.getLocalFile( filePath );
RemoteWebElement input = (RemoteWebElement) driver.findElement(By.xpath( locator ));
input.setFileDetector(detector);
input.sendKeys(localFile.getAbsolutePath());
input.click();


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, FILE_DETECTOR;
}
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 if ( type == ActionType.FILE_DETECTOR ) {
        LocalFileDetector detector = new LocalFileDetector();
        File localFile = detector.getLocalFile( filePath );
        RemoteWebElement input = (RemoteWebElement) driver.findElement(By.xpath(locator));
        input.setFileDetector(detector);
        input.sendKeys(localFile.getAbsolutePath());
        input.click();
        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();
}

Using Selenium: sendKeys() When you want to transfer a file (Refer a local file) form your local computer to the Grid-Node server, you need to use setFileDetector method. By using this Selenium-Client will transfer the file through the JSON Wire Protocol. For more information see saucelabs fileUpload Example

driver.setFileDetector(new LocalFileDetector());
Disgraceful answered 27/9, 2017 at 11:51 Comment(0)
L
0

If you are using Mac and looking for an easy way that work with Robot:

  1. If it is a Mac machine Ctrl+V will not work, you need to use cmd+v instead.(use VK_META for CMD key).
  2. You need to provide specific permissions to your IDE to access the device. Please refer to this article for permissions:

Java.awt.Robot keyPress and keyRelease not working at all

  1. When you use robot after clicking on the upload button a Java app open and the browser loses focus(use CMD+TAB to get back to the previous app), Please use the below code as the same work in my case
        //click on button to open upload dialog
        driver.findElement(By.xpath("sample/xpath")).click();

        // Create a new Robot instance
        Robot robot = new Robot();
        Thread.sleep(2000);

        //File Need to be imported
        File file = new File("/Users/username/Documents/sampleFile.pdf");
        StringSelection stringSelection = new StringSelection(file.getAbsolutePath());

        //Copy to clipboard
        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);

        // Cmd + Tab is needed since it launches a Java app and the browser looses focus
        robot.keyPress(KeyEvent.VK_META);
        robot.keyPress(KeyEvent.VK_TAB);
        robot.keyRelease(KeyEvent.VK_META);
        robot.keyRelease(KeyEvent.VK_TAB);
        robot.delay(500);

        //Open Goto window CMD+SHIFT+G
        robot.keyPress(KeyEvent.VK_META);
        robot.keyPress(KeyEvent.VK_SHIFT);
        robot.keyPress(KeyEvent.VK_G);
        robot.keyRelease(KeyEvent.VK_META);
        robot.keyRelease(KeyEvent.VK_SHIFT);
        robot.keyRelease(KeyEvent.VK_G);
        robot.delay(500);


        //Paste the clipboard value CMD+V
        robot.keyPress(KeyEvent.VK_META);
        robot.keyPress(KeyEvent.VK_V);
        robot.keyRelease(KeyEvent.VK_META);
        robot.keyRelease(KeyEvent.VK_V);
        robot.delay(500);


        //Press Enter key to close the Goto window and Upload window
        robot.keyPress(KeyEvent.VK_ENTER);
        robot.keyRelease(KeyEvent.VK_ENTER);
        robot.delay(500);

        robot.keyPress(KeyEvent.VK_ENTER);
        robot.keyRelease(KeyEvent.VK_ENTER);
        robot.delay(500);

        robot.keyPress(KeyEvent.VK_ENTER);
        robot.keyRelease(KeyEvent.VK_ENTER);
        robot.delay(500);


  1. Note that, after every key release you need to add some delay to make it work. Also, key combinations may vary on usecase.
Labyrinthine answered 9/5, 2023 at 18:31 Comment(0)
P
-1

or may use webdriver backed selenium -

Selenium selenium = new WebDriverBackedSelenium(driver, baseUrl);

and do the usual type on upload element -

selenium.sendKeys("file path")
Perren answered 6/10, 2011 at 7:0 Comment(1)
I think, your answer seems incomplete, that means not properly described. At least I don't understand how to use it in my case.Moreover

© 2022 - 2024 — McMap. All rights reserved.