Webdriver: File Upload
You can set the value of your input field using JavaScript. Considering that the id of the field is fileName
the following example will set the value of the input to the file C:\temp\file.txt
:
String script = "document.getElementById('fileName').value='" + "C:\\\\temp\\\\file.txt" + "';";
((IJavaScriptExecutor)driver).ExecuteScript(script);
In this example, driver
is your WebDriver instance.
Please note that you have to use four backslashes (\
) for Windows-like paths because you are required to pass double back-slashes to the JavaScript so you have to escape both with two additional slashes. The other option is to use a forward slash (e.g. "C:/tmp/file.txt"
) and that should also work.
You can do this without injecting JavaScript. You just need to get hold of the form field and type into it. Something like (using the Ruby API):
driver.find_element(:id, 'upload').send_keys('/foo/bar')
For C#, SendKeys()
works but you have to use \
in your file path instead of /
For example, the follow works :
string filePath = @"drive:\path\filename.filextension";
driver.FindElement(By.Id("fileInput")).SendKeys(filePath);
But the following doesn't work :
string filePath = "drive:/path/filename.filextension";
driver.FindElement(By.Id("fileInput")).SendKeys(filePath);