Dustin N.
Dustin N.

Reputation: 795

Selenium WebDriver - Upload document to non-input button

I am needing to upload a document via Selenium WebDriver using Chromedriver. I have tried all the Action class and Javascript stuff, but those do not work. I am assuming they do not work because those are relying on the button to be an input field, however, the upload button I'm dealing with is not. It's HTML looks like this:

<a id="Dialogs_Dialogs_lbAttachUpload" onclick="return ButtonVerifyEnabled(this, ShowFileSelect);" class="SkinButton sbBlue" onmouseover="ButtonHover(this,30);" onmouseout="ButtonLeave(this);" onmousedown="ButtonDown(this,30);" onmouseup="ButtonHover(this,30);" skinheight="30" style="color: white; width: 132px; height: 30px; line-height: 30px; background-position: 0px 0px;" title=""><div class="SkinButtonLeft" style="background-position: 0px 0px;"></div><div class="SkinButtonRight" style="background-position: -4px 0px;"></div>Upload documents</a>

I have AutoIT and Sikuli implemented and working, but the problem with those solutions is I cannot get them to work when running the Selenium tests via Jenkins.

My latest attempt looks like this:

    WebElement upload = SConfirmOrder.uploadDocuments_btn(driver);
    Actions actions = new Actions(driver);
    actions.moveToElement(upload);
    actions.sendKeys("filepath\\Test PDF.pdf");

It runs through successfully, but no document actually gets uploaded.

Upvotes: 5

Views: 5334

Answers (1)

Florent B.
Florent B.

Reputation: 42518

The browser cannot upload a file without an <input> element, unless the file is dropped from the desktop. It would be a security breach to be able to upload a file by code.

So in your case, the<input> is probably created once the user has clicked the link.

One way to handle this case is to silence the click event, click the link and then set the file to the <input>:

// disable the click event on an `<input>` file
((JavascriptExecutor)driver).executeScript(
    "HTMLInputElement.prototype.click = function() {                     " +
    "  if(this.type !== 'file') HTMLElement.prototype.click.call(this);  " +
    "};                                                                  " );

// trigger the upload
driver.findElement(By.id("Dialogs_Dialogs_lbAttachUpload"))
      .click();

// assign the file to the `<input>`
driver.findElement(By.cssSelector("input[type=file]"))
      .sendKeys("filepath\\Test PDF.pdf");

Note that you may also need to wait for the <input> to be created.

Upvotes: 11

Related Questions