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.
We have discussed uploading a file using using Webdriver Sendkeys method and Using AutoIT Tool. Now here we will look into an other way of doing file upload using Robot class and StringSelection class in java. Robot class is used to (generate native system input events) take the control of mouse and keyboard.
We can upload files using Selenium Webdriver. This is achieved by the sendKeys method. We have to first identify the element which performs the file selection by mentioning the file path [to be uploaded].
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With