Best Practices & Tips: Selenium File Upload

Posted by Sauce Labs

Learn how to upload a file using Selenium WebDriver with Sauce Labs’ guide.

In this tutorial, we’ll cover how to upload files using Webdriver’s native file upload feature.

As you may know, the way to address this in Selenium 1 is to place your files in an accessible web server and use the attachFile command that points to the correct URL. With Selenium 3, the Selenium Dev team has continued the interface from selenium2, using a local file and the sendKeys command.

This works like a charm in all drivers. When moving this test to a remote server (such as, for example, our Selenium 2 Cloud), all you need to do is use the setFileDetector method to let WebDriver know that you’re uploading files from your local computer to a remote server instead of just typing a path. Almost magically, the file will be base64 encoded and sent transparently through the JSON Wire Protocol for you before writing the fixed remote path. This is an excellent solution, as it lets you switch your tests from a local to remote Driver without having to worry about changing your tests’ code.

This feature is available in all the official Selenium 3 bindings, just make sure Selenium 2.8.0 or newer is used as this feature has been released then. Here are some examples tests:

Java

import java.util.*;
import java.net.*;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.Keys;
import org.openqa.selenium.Platform;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.remote.LocalFileDetector;
import java.util.concurrent.TimeUnit;
import java.net.URL;

public static void main(String[] args)  {

System.setProperty("webdriver.chrome.driver","./chromedriver");

       DesiredCapabilities capabillities = DesiredCapabilities.chrome();


       String USERNAME = "USERNAME";
       String ACCESS_KEY = "ACCESS_KEY";
       String url =  "https://" + USERNAME + ":" + ACCESS_KEY + "@ondemand.saucelabs.com:443/wd/hub";


       URL start_url;
       try {
           start_url = new URL(url);
       } catch(MalformedURLException ex) {
           return;        }

       driver.get("http://xndev.com/display-image/");

       RemoteWebDriver driver = new RemoteWebDriver(start_url, capabillities);
       driver.setFileDetector(new LocalFileDetector());<

       WebElement upload = driver.findElement(By.xpath("//*[@id='post-2554']/div/input"));

    //In windows the slash below will need to be reversed
       upload.sendKeys(System.getProperty("user.dir") + '/' + "broken_bulb.jpg");https://docs.google.com/document/d/1CnPToQhspWKjHwvF4NVa04-J2KBJaeuPj1dQ3jeK3fk/edit?usp=sharing        WebElement img = driver.findElement(By.xpath("//img['data:image/jpeg;base64'=substring(@src,1,22)]"));https://docs.google.com/document/d/1CnPToQhspWKjHwvF4NVa04-J2KBJaeuPj1dQ3jeK3fk/edit?usp=sharing

       driver.quit();   

View the code hosted with love by GitHub.

Note to run this code in windows you will need to change the direction of the slash. You’ll also need to either add your sauce labs login or else change the comments in the raw code to run it locally.

Ruby

require 'rubygems'
require "test/unit"
require 'selenium-webdriver'
class ExampleTest < Test::Unit::TestCase
 def setup
caps = Selenium::WebDriver::Remote::Capabilities.chrome()   
caps['platform'] = 'Windows 10'
   caps['version'] = '72.0'
   caps[:name] = "Remote File Upload using Selenium 3 with Ruby"
   caps['selenium-version'] = "3.14.0"
   @driver = Selenium::WebDriver.for(
     :remote,
     :url => "http://USERNAME:ACCESS_KEY@ondemand.saucelabs.com:80/wd/hub",
     :desired_capabilities => caps)
   @driver.file_detector = lambda do |args|
      # args => ["/path/to/file"]
      str = args.first.to_s
      str if File.exist?(str)
   end
end

 def test_sauce
   @driver.navigate.to "http://xndev.com/display-image/"
   element = @driver.find_element(:xpath, "//*[@id='post-2122']/div/input")
   directory = File.expand_path File.dirname(__FILE__)

    #Note for windows the slash will need to be switched"
   #file://
   specific_filename = directory + "/" + "broken_bulb.jpg"
   element.send_keys specific_filename

    object = @driver.find_element(:xpath, "//img['data:image/jpeg;base64'=substring(@src,1,22)]")

    assert true
end

def teardown
   @driver.quit
end

end

View the source code hosted with love by GitHub

Pro tip: Write your own FileHandler that will use special codes to represent files before typing paths (locally) or uploading them (remotely). Example: “test-file:small-image”

Sauce Labs - Selenium Testing on the Cloud

Sauce Labs makes automated testing awesome. Our cloud-based platform helps developers test native & hybrid mobile and web applications across hundreds of browser / OS platforms, including iOS, Android & Mac OS X. Sauce supports Selenium, Appium and popular JavaScript unit testing frameworks, and integrates with all of the top programming languages, test frameworks and CI systems. With built-in video recording and screenshots of every test case, debugging tools, and secure tunneling for local or firewalled testing, Sauce makes running, debugging and scaling test suites quick and easy.


Free Trial

Get access to a free 14-day trial version, or contact Sales for more information.