7

I have following method that uploads image using selenium.

public static void uploadSampleImage(StaticSeleniumDriver driver)
{
    File file = new File(System.getProperty("user.dir") + "/resources/images/" + SAMPLE_DOCUMENT_FILE_NAME);
    Utils.Log("file exists: " + file.exists());

    String imagePath = file.getAbsolutePath();
    WebElement input = driver.findElement(By.name("file"));
    input.sendKeys(imagePath);
}

That's a standard way of feeding file path (like explained in Guru99 tutorial) to upload file.

  1. It works fine when testing locally on windows
  2. It is NOT working when run inside docker container (linux), getting this error:

org.openqa.selenium.InvalidArgumentException: invalid argument: File not found : /usr/src/app/resources/images/image2.png (Session info: chrome=72.0.3626.81) (Driver info: chromedriver=2.46.628388 (4a34a70827ac54148e092aafb70504c4ea7ae926),platform=Linux 4.9.125-linuxkit x86_64) (WARNING: The server did not provide any stacktrace information)

Which is weird because I am sure file exist in given directory (in my method above, I am checking if file exists and log clearly confirms that)

enter image description here

Any suggestions would be welcome, thank you

Matthewek
  • 1,519
  • 2
  • 22
  • 42

2 Answers2

8

For RemoteWebDriver you have to set file detector driver.setFileDetector(new LocalFileDetector());. Your code:

public static void uploadSampleImage(StaticSeleniumDriver driver)
{
    driver.setFileDetector(new LocalFileDetector());
    File file = new File(System.getProperty("user.dir") + "/resources/images/" + SAMPLE_DOCUMENT_FILE_NAME);
    Utils.Log("file exists: " + file.exists());

    String imagePath = file.getAbsolutePath();
    WebElement input = driver.findElement(By.name("file"));
    input.sendKeys(imagePath);
}
Sers
  • 12,047
  • 2
  • 12
  • 31
0

Instead of using '/' in your path string, you can use File.separator which takes care of the OS level file separator automatically under the hood. Using this, your code becomes independent of any OS, and it lets Java take care of what separator to use as per the OS instead of you worrying about it.

So the first line of code becomes:

new File(System.getProperty("user.dir") + File.separator + "resources" + File.separator + "images" + File.separator + SAMPLE_DOCUMENT_FILE_NAME);

and rest of the line remains same.

!! No extra headaches.

Ayush Choudhary
  • 321
  • 4
  • 10