Ankit Jain
Ankit Jain

Reputation: 808

File Upload functionality of Selenium web driver not working through sendkeys

Steps to reproduce:-

Go to :-

https://talentconnect.pge.com/sap/bc/webdynpro/sap/hrrcf_a_unreg_job_search?sap-client=810&sap-wd-configId=ZPERJ_A_UNREG_JOB_SEARCH#

Username:- [email protected] Password:- 1Selenium@

Search and Apply for any Job and go upto Attachment Page, and then click Add Button. I am not able to Upload any file through Selenium here.

1) I am using sendkeys to Answer docType, and docName question.

2) Browse element is in a form, so I am first sending file path using sendkeys, and then calling submit function on form element.

3) After that I am clicking on Upload button.

Problem seems to be in handling browse button, in chromedriver, if I go upto browse tab, browse file manually and then run rest part through code then file gets uploaded successfully.

I am using below code to browse and upload.

List<WebElement> attachButtons = driver.getDriver().findElements(By.xpath("//input[@type=\"file\"]"));
for (int i = 0; i < 5; i++)
{
    if (attachButtons != null && attachButtons.size() > 0 && attachButtons.get(0).isDisplayed())
    {
        attachButtons.get(0).sendKeys("/home/user/path/to/file");
        SeleniumUtils.pause(1 * 1000);
        List<WebElement> formElements = driver.getDriver().findElements(By.tagName("form"));
        if(formElements != null && formElements.size() > 0)
        {
            formElements.get(0).submit();
        }
        break;
    }
    SeleniumUtils.pause(3 * 1000);
}
List<WebElement> uploadButtons = driver.getDriver().findElements(By.xpath("//a[@ct=\"B\"]"));
if (uploadButtons != null && uploadButtons.size() > 0)
{
    WebElement uploadButton = null;
    for(WebElement button : uploadButtons)
    {
        if(button.isDisplayed() && button.getText().contains("Upload"))
        {
            uploadButton = button;
            break;
        }
    }
    if(uploadButton != null)
    {
        uploadButtons.get(0).click();
    }
}

Any help is greatly Appreciated.

Thanks!

Upvotes: 1

Views: 9540

Answers (1)

Husam
Husam

Reputation: 1105

I faced a similar problem. It was resolved by using getAbsolutePath. Try the following code and see if it helps.

File file = new File("/home/user/path/to/file");
attachButtons.get(0).sendKeys(file.getAbsolutePath());

Another way is to use java script. You may use JavaScriptExecutor, as follows:

String jsScript = "var input = document.getElementsByTagName('input')[0];"
        +"input.value='/home/user/path/to/file';";
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript(jsScript);

Upvotes: 0

Related Questions