Home > Software design >  Unable to upload image using Upload button using Java and Selenium
Unable to upload image using Upload button using Java and Selenium

Time:11-09

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.

CodePudding user response:

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();

CodePudding user response:

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");
  • Related