Selecting and uploading files in Selenium

Selecting and uploading files while running your tests on local machine

Uploading files in Selenium Webdriver is quite easy. You just have to sendkeys your local file path to file upload element.

This is how your file upload element looks like,
fileupload
This is just a plan HTML input element just like textfield but with type ‘file’,
fileuploadhtml
When you click on ‘Choose File’ button, OS native file select dialog will be opened. This dialog will not be recognized by your driver, so when uploading any file in Selenium you should never click on ‘Choose File’ button. Instead, just use sendkeys to select the file,

WebElement El = driver.findElement(By.id("'fileUploadField'"));
El.sendKeys("c:\\temp\\test.txt");

This will select your file without having to select it through file select dialog. This works flawlessly across all supported drivers.

Selecting and uploading files while running your tests on Selenium Grid

If you are running your tests on grid then you should let your remote driver know that the file that needs to be uploaded is residing on local machine and not on remote machine. This can be achieved by setting LocalFileDetector for RemoteWebElement,

WebElement El = driver.findElement(By.id("'fileUploadField'"));
((RemoteWebElement) El ).setFileDetector(new LocalFileDetector()); 
El.sendKeys("c:\\temp\\test.txt");

Here you are setting local file detector for file upload element, so whenever you use sendkeys on this element, your RemoteWebDriver uses this file detector object to detect the file. If the file is detected then it will be base64 encoded and uploaded to remote server through JSON Wire Protocol and the remote fixed path will be selected as file path.