img

Selenium File Upload Techniques

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.

 


WinWaitActive("File Upload")

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.

 


public void UploadFileUsingAutoIt()
throws InterruptedException, IOException {

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

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

Thread.sleep(1000);

driver.findElement(By.id("uploadfile")).click();

Thread.sleep(1000);

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.

 


public void UploadFileUsingSendKeys()
throws InterruptedException {

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

WebElement fileInput = driver.findElement(By.name("uploadfile"));
fileInput.sendKeys(filepath);

Thread.sleep(1000);

driver.findElement(By.id("uploadfile")).sendKeys(
"C:\\path\\to\\fileToUpload.txt");

Thread.sleep(1000);

fileInput.sendKeys(filepath);
}

 

  • Facebook
  • Twitter
  • Google+
  • Linkedin
  • Pinterest

Leave a Comment

Your email address will not be published. Required fields are marked *

It is main inner container footer text