Selecting and uploading files in Selenium

Selecting and uploading files while running your tests on local machine

Uploading files in Selenium Webdriver is quite easy. You just have to sendkeys your local file path to file upload element.

This is how your file upload element looks like,
fileupload
This is just a plan HTML input element just like textfield but with type ‘file’,
fileuploadhtml
When you click on ‘Choose File’ button, OS native file select dialog will be opened. This dialog will not be recognized by your driver, so when uploading any file in Selenium you should never click on ‘Choose File’ button. Instead, just use sendkeys to select the file,

WebElement El = driver.findElement(By.id("'fileUploadField'"));
El.sendKeys("c:\\temp\\test.txt");

This will select your file without having to select it through file select dialog. This works flawlessly across all supported drivers.

Selecting and uploading files while running your tests on Selenium Grid

If you are running your tests on grid then you should let your remote driver know that the file that needs to be uploaded is residing on local machine and not on remote machine. This can be achieved by setting LocalFileDetector for RemoteWebElement,

WebElement El = driver.findElement(By.id("'fileUploadField'"));
((RemoteWebElement) El ).setFileDetector(new LocalFileDetector()); 
El.sendKeys("c:\\temp\\test.txt");

Here you are setting local file detector for file upload element, so whenever you use sendkeys on this element, your RemoteWebDriver uses this file detector object to detect the file. If the file is detected then it will be base64 encoded and uploaded to remote server through JSON Wire Protocol and the remote fixed path will be selected as file path.

23 thoughts on “Selecting and uploading files in Selenium

  1. It doesn’t work for me. I got the File Upload dialog and nothing happened then. Here is my code:
    driver.get(“http://vm-stapp-50:3000/portal-kar/kar-questions-restricted-by-file.html?portallang=en”);
    button1 = driver.findElement(By.xpath(“//*[@id=’fileupload’]/div[2]/div[1]/span[1]”)).getText();
    System.out.println(“\nButton1: ” + button1);
    //driver.findElement(By.cssSelector(“.btn.button.fileinput-button > span”)).click();
    driver.findElement(By.cssSelector(“.btn.button.fileinput-button > span”)).sendKeys(“X:\\test_kar.xlsx”);

    html code looks like this:


    Velg fil

      • In my case, I’m targeting the input element only and when I upload a file it falls under the element, but it is not showing. when I hover my mouse to the button the tooltip shows my file name.

  2. i have been tried your solution but i get this error :

    java.lang.AssertionError: Unrecognized command: POST /session/3f1fb726-bae5-43ee-a92f-9417bb084c56/file
    I don’t know what is the problem

    • I have seen this issue for IE driver while running locally. Should work fine for Chrome and Firefox. Also, there should be no issues while running on grid. Try to get the latest driver for Chrome and IE based on your Selenium version.

      • hi, actually i am also getting same error “org.openqa.selenium.UnsupportedCommandException: Unrecognized command: POST /session/e7431514-425a-45ba-8c66-5c7a7659fc3b/file”

        can you plz tell me the solution i could not find ans so….

      • It is not working for Firefox as well, I have the latest version of Selenium and Firefox.

        Getting this –
        org.openqa.selenium.UnsupportedCommandException: Unrecognized command: POST /session/fd481a91-f664-114b-8363-f4a64ee30518/file
        Command duration or timeout: 18 milliseconds
        Build info: version: ‘2.53.0’, revision: ’35ae25b1534ae328c771e0856c93e187490ca824′, time: ‘2016-03-15 10:43:46’
        System info: host: ‘Vaibhav.local’, ip: ‘172.20.57.75’, os.name: ‘Mac OS X’, os.arch: ‘x86_64’, os.version: ‘10.10.5’, java.version: ‘1.8.0_66’
        Driver info: org.openqa.selenium.firefox.FirefoxDriver
        Capabilities [{applicationCacheEnabled=true, rotatable=false, handlesAlerts=true, databaseEnabled=true, version=46.0.1, platform=MAC, nativeEvents=false, acceptSslCerts=true, webStorageEnabled=true, locationContextEnabled=false, browserName=firefox, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true}]
        Session ID: fd481a91-f664-114b-8363-f4a64ee30518

  3. Doesn’t work for me either. I am sure I have the correct input/type=file element and I’m sure it’s visible, but that code:

    WebElement file = driver.findElement(By.xpath(“//input[@type=’file’]”));
    file.sendKeys(“/tmp/myfile.txt”);

    Just throws:

    org.openqa.selenium.ElementNotVisibleException: You may only interact with visible elements

    Any ideas?

  4. Greatest thing ever. Worked for FF the first time I tried it. Was beating head against wall trying to sendkeys to the Open File dialog box. This is wonderful.

  5. String file_path = utility.getCellData(1, 2);
    System.out.println(file_path);

    LocalFileDetector detector = new LocalFileDetector();
    // File file = detector.getLocalFile(file_path);

    File file = new File(file_path);
    file.toURI();
    RemoteWebElement element1=(RemoteWebElement) ((RemoteWebDriver) driver).findElement(By.id(“definitionFile”));
    element1.click();
    if(isGrid){
    ( (RemoteWebElement) element1) .setFileDetector( detector );
    }
    element1.sendKeys(file.getAbsolutePath());

    // Process_Def.bttn_Browse(driver).sendKeys(file.getAbsolutePath());
    Process_Def.click_Upload(driver).click();
    Swimlane.wait(driver);

    Html code to the box:

    PAR File:

    help me friends i don’t know yy i am not able to pass the value to text box.

  6. Thank you very much! It was so useful.
    I want to comment that i am using windows 10 so i was getting an error message
    Uncaught WebDriverError: unknown error: path is not absolute: C:UsersmyyserDocumentsmyfile.txt
    because i was using C:\Users\myuser\Documents\myfile.txt
    To solve that problem i tried using double \\
    C:\\Users\\myuser\\Documents\\myfile.txt
    And now is working good

  7. self.driver.get(“http://the-internet.herokuapp.com/upload”)
    file_up_element= driver.find_element_by_id(“file-upload”)
    upload=driver.find_elements_by_id(“file-submit”)
    print file_location
    file_up_element.send_keys(file_location)

    It doesn’t seem to work, any ideas,

  8. Hi, It works. But in my scenario:
    I click to add an image container -> the dialog will appear automatically. And I cannot close this dialog to upload file directly using your solution.
    I’m using Ruby + watir
    Thank you

  9. Hello,

    I am using the send_keys method but it does not work.
    I am using something like this:-

    browser.find_element_by_xpath(“//label[@………..]”).click() # this works perfectly and the dialog box opens..

    Now when i do the following, i.e. the method where i don’t click and perform the send_keys (path)
    browser.find_element_by_xpath(“//label[@………..]”).send_keys(“desired path”) # this gives an exception “cannot focus element”

    Can you please help me with this. I am using chromedirver (2.30 latest) and python 3.6

    Thanks

  10. Hi All, I am getting Null pointer Exception on the line File.getAbsolutePath() in below code when i am trying to find the file existence on remote machine
    public static boolean verifyFileExistence(String browser, String fileName, WebDriver driver) throws IOException {
    File file = null;
    String home = System.getProperty(“user.home”);
    String filePath = home + “/Downloads/” + fileName;
    if (browser.contains(“grid”)) {
    Logger.getTest().log(LogStatus.INFO, “Executing on the Remote machile”, “Checking Presence of file on Remote Machine :” + browser);
    LocalFileDetector detector = new LocalFileDetector();
    file = detector.getLocalFile(filePath);
    ((RemoteWebDriver) driver).setFileDetector(detector);
    file.getAbsolutePath();

    } else {
    Logger.getTest().log(LogStatus.INFO, “Executing on the Remote machine”, “Checking Presence of file on local Machile :” + browser);
    file = new File(filePath);
    }

    if (file.exists() && !file.isDirectory()) {

    Logger.getTest().log(LogStatus.INFO, “Checking the File existence”, “File found succesfully in the location :” + fileName);
    return true;
    } else {
    Logger.getTest().log(LogStatus.ERROR, “Checking the File existence”, “File not found in the location :” + fileName);
    return false;
    }
    }

Leave a comment