Uploading a file is a common piece of functionality found on the web. But when trying to automate it you get prompted with a with a dialog box that is just out of reach for Selenium.

In these cases, people often look to a third-party tool to manipulate this window (e.g., AutoIt). While this can help solve your short-term need, it sets you up for failure later by chaining you to a specific platform (e.g., AutoIt only works on Windows), effectively limiting your ability to test this functionality on different browser & operating system combinations.

Firstly create a new file in your Eclipse project and name it as <File_Upload_Example>. Add the following AutoIt script code into the newly created file. This script accepts a single argument which is the path of the file to upload. It’ll help us handle file upload window. We’ll execute this file from Java code using the <Runtime.getRuntime().exec()> method.



Send(\$CmdLine[1])

Send("{ENTER}")



Now, find out the Java code that opens the file upload window and runs the AutoIt script mentioned above to carry out the file upload.


throws InterruptedException, IOException {

String workingDir = System.getProperty("user.dir");
String autoitscriptpath = workingDir + "\\"

driver = new FirefoxDriver();
String filepath = workingDir + "\\SeleniumWebdriverUploadFile.html";
driver.get(filepath);

Runtime.getRuntime().exec(
"cmd.exe /c Start AutoIt3.exe " + autoitscriptpath + " \""
+ filepath + "\"");
}



Another the most basic technique to perform the upload of a file. Simply, get the file upload element either by using the Id or Name. And call the Webdriver’s sendKeys() method to set the value of the file to upload. Check out the below code for clarity. You can add it as is to your project. Please make sure to replace the Id/Name accordingly.


throws InterruptedException {

driver = new FirefoxDriver();
String workingDir = System.getProperty("user.dir");
String filepath = workingDir + "\\SeleniumWebdriverUploadFile.html";
driver.get(filepath);

fileInput.sendKeys(filepath);

fileInput.sendKeys(filepath);
}