How to Upload File Using Selenium Webdriver in Java

How to upload file using Selenium Webdriver?

Below code solved the issue..

cd.findElement(By.id("import_file")).sendKeys("E:\\iMedicor-Karthik\\2.Demographi‌​cs\\Patients_Data\\Patient_One.xml");

Actually the filepath caused a issue for me.. I have used

E:\\iMedicor-Karthik\\2.Demographics\\Patients_Data\\Patient_One.xml

instead of E://iMedicor-Karthik/2.Demographics/Patients_Data/Patient_One.xml

How to upload a file by transfering the file from the local machine to the remote web server using Selenium Grid

This error message...

Exception in thread "main" org.openqa.selenium.InvalidArgumentException: Attempting to upload file 'C:\daten\test2.xml' which does not exist.

...implies that the desired file doesn't exist on the client machine.



Local file detector

The Local File Detector allows the transfer of files from the client machine to the remote server. In case a test needs to upload a file to a web application, a remote WebDriver can automatically transfer the file from the local machine to the remote web server during runtime. This allows the file to be uploaded from the remote machine running the test. It is not enabled by default and can be enabled as follows:

  • Java:

    driver.setFileDetector(new LocalFileDetector());
  • Python:

    from selenium.webdriver.remote.file_detector import LocalFileDetector

    driver.file_detector = LocalFileDetector()
  • C#:

    var allowsDetection = this.driver as IAllowsFileDetection;
    if (allowsDetection != null)
    {
    allowsDetection.FileDetector = new LocalFileDetector();
    }
  • Ruby:

    @driver.file_detector = lambda do |args|
    # args => ["/path/to/file"]
    str = args.first.to_s
    str if File.exist?(str)
    end
  • JavaScript:

    var remote = require('selenium-webdriver/remote');
    driver.setFileDetector(new remote.FileDetector);
  • Kotlin:

    driver.fileDetector = LocalFileDetector()


This usecase

If you are running your tests on Selenium Grid then you need to let your remote driver know that the file that needs to be uploaded is residing on the local machine and not on remote machine. In those cases, to upload a file from the client machine to the remote server, WebDriver can automatically transfer the file from the local machine to the remote web server during runtime you can use the following code block:

WebElement addFile = driver.findElement(By.xpath("//input[@type='file']"));
((RemoteWebElement)addFile).setFileDetector(new LocalFileDetector());
addFile.sendKeys("C:\\daten\\test2.xml");


Outro

Selecting and uploading files while running your tests on Selenium Grid



Related Topics



Leave a reply



Submit