0

trying to upload a an image file using Java selenium

Hi all, I am trying to upload a an image file using Java selenium

below is the code:
first approach:

WebElement upload_file = driver.findElement(By.xpath("xpath of upload button"));
upload_file .click();
// just passed a delay, it does not crate a problem I can remove it
java.lang.Thread.sleep(2000); 
//full file path present in my local machine
        uplaod_file.sendKeys("C:\\Users\\Lenovo\\Pictures\\Files\\image.jpg");
        System.out.println("File is Uploaded Successfully");

Issue observed :org.openqa.selenium.ElementNotInteractableException: element not interactable

Second approach:

        By upload_file_button = By.xpath("xpath of upload button");
        explicit_wait.until(ExpectedConditions.elementToBeClickable(upload_file_button));
        driver.findElement(upload_file_button).click();
        java.lang.Thread.sleep(2000);
        ((WebElement) upload_file_button).sendKeys("C:\\Users\\Lenovo\\Pictures\\Files\\image.jpg");
        System.out.println("File is Uploaded Successfully");

Issue observed : org.openqa.selenium.TimeoutException: Expected condition failed: waiting for element to be clickable: xpath of upload button (tried for 20 second(s) with 500 milliseconds interval)

need help for same, please do correct me If I am wrong.

2 Answers 2

2

Uploading file by Selenium is normally done as following:
You can send the uploading file full path to the special element on the web page. This is not the "Upload" visible button but a special element with input tag name and type attribute with file value. As a user you can't see it on the page but can find it with use of dev tools. So, this element can be located by the following XPath: //input[@type='file'].
So, to upload your file try this:

driver.findElement(By.xpath("//input[@type='file']")).sendKeys("C:\\Users\\Lenovo\\Pictures\\Files\\image.jpg");
Sign up to request clarification or add additional context in comments.

2 Comments

Hey Prophet, you really are a prophet. it worked out ... thanks
No, I'm not a real prophet. Also not a genius. Just somewhat experienced :)
0

No, you don't click on the upload file prompt, you are just sending it the file's path. Later, click on the send / upload file button.

upload_file.sendKeys("C:\\Users\\Lenovo\\Pictures\\Files\\image.jpg");
upload_button = driver.findElement(By.Xpath, '//*[text()="upload"]');
upload_button.click();

1 Comment

Thanks @Tal Angel , but facing issue Below is my modified code: WebElement browse = driver.findElement(By.xpath("//*[@id=\"__next\"]/div[2]/div/main/div/div[1]/div[1]/label")); browse.sendKeys("C:\\Users\\Lenovo\\Pictures\\Files\\nft.jpg"); browse.click();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.