Search code examples
c#seleniumwebdriversaucelabs

How to upload image to web page in Saucelabs test by Selenium in c#?


I must upload any image to web page to create online shop to move on test. I have to click on button for uploading after that I have to give directory of the file, but I can't give local directory because test runs on VM on Saucelabs. How to solve this problem?


Solution

  • Use the LocalFileDetector class. Your code will look something like this:

    // WARNING!! Untested code written from memory, without benefit of an IDE.
    // May not work exactly correctly or even compile without modification. 
    // Assume driver is a properly instantiated IWebDriver object, which is
    // to be used with a remote service (including SauceLabs or similar).
    IAllowsFileDetection fileDetectionDriver = driver as IAllowsFileDetection;
    fileDetectionDriver.FileDetector = new LocalFileDetector();
    
    IWebElement fileElement = driver.FindElement(By.Id("idOfFileInputElement"));
    fileElement.SendKeys(@"C:\path\to\local.file");
    

    By setting the file detector, the SendKeys method will first upload the file from your local system to the remote machine on which the code is actually running. Then SendKeys will set the file in the <input> element, using the local file path on the remote machine.