Skip to content

Setting the filepath for HTML input-file-fields with WebDriver

Posted on:December 16, 2011

My coworker could not get Selenium’s WebDriver to select a file for upload for the following HTML input field:

<input type="file" name="filename" />

The problem is that the clicking the input field opens a OS-specific file selection window that WebDriver cannot interact with. Her initial approach was to call an external program controls that file selection window and picks the file she wanted to upload. The approach is described here. The approach works, but it binds us to a Windows-only implementation.

After some searching, I notice that Watir-WebDriver is able to set the filepath on the input directly. If watir can do it directly, why can’t we? Watir would either have its own implementation or be wrapping the WebDriver ruby binding. Turns out it’s doing the latter, which is great for us. We can use the same implementation that watir uses, inside our choosen language, java.

Here are code snippets for both java and ruby:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

WebDriver browser = new FirefoxDriver();
require 'selenium-webdriver'

browser = WebDriver::Browser.for(:firefox)
browser.find_element(:name, "filename").send_keys("/path/to/my/file")