JustToKnow
JustToKnow

Reputation: 823

Windows file pop up wont add my file in Selenium & JAVA. Why

I'm trying to upload a file within the windows pop up after clicking on a button:

enter image description here

After clicking on that button a pop up in shown:

enter image description here

I click on that button by using this:

driver.findElement(By.xpath("//*[@id=\"div-add-file\"]/a")).click();

Then, i used this:

driver.switchTo().activeElement().sendKeys("C:\\Users\\Steve\\Downloads\\01004185FCA003900517097.pdf");

It did not work.

I tried to do something like that avoiding clicking on the button but sending the file path:

driver.findElement(By.xpath("//*[@id=\"div-add-file\"]/a")).sendKeys("C:\\Users\\Maxi\\Downloads\\01004185FCA003900517097.pdf");

but it wont work.

Am i doing anything wrong?

Upvotes: 0

Views: 325

Answers (1)

Prophet
Prophet

Reputation: 33361

Uploading a file with Selenium is done by sending a path to the uploaded file to a special element on the page. This element can normally be located by this XPath: //input[@type='file']
So your command could be something like the following:

driver.findElement(By.xpath("//input[@type='file']")).sendKeys("C:\\Users\\Maxi\\Downloads\\01004185FCA003900517097.pdf");

Maybe you will need to add some delay to make the page loaded. If so WebDriverWait should be used.

WebDriverWait wait = new WebDriverWait(webDriver, timeoutInSeconds);
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//input[@type='file']"))).sendKeys("C:\\Users\\Maxi\\Downloads\\01004185FCA003900517097.pdf");

Sometimes several more that 1 inputs matching the above locator will be on the same page and sometimes there will be no such element.
In case there are more than 1 elements matching the above locator we will need to find the precise, unique locator.
In case of no such element we will have to find another approach to upload file.

Upvotes: 1

Related Questions