How To Upload File Use Selenium WebDriver

Upload files is a very general function on the web. But when you want to implement it in selenium testing automation script, a dialog box will always popup which selenium can not handle.

There is a very easy way to resolve this problem. You just need to find the file input web element and type the uploaded file’s absolute path ( as string) into it, then submit the form.

This method works only when the file input text box  is visible and enabled.

First let us look at the html code below.

<!--This is just the html form which include the upload file textbox -->
<form enctype="multipart/form-data" action="receiveFile.html" method="post"> 

  <p>Browse and upload file: </p>
  <input type="file" name="uploadFileInputBox">

  <!-- This is the form submit button -->
  <input type="submit" value="Upload File" name="uploadFileSubmitBtn">


You can see that the upload file web element’s name is “uploadFileInputBox”, and we set it’s value to the uploaded file’s absolute path (as string).

Following is just the java code for selenium testing, you can see detail information from code comments. You should remember that you should not click the Browse button for the web element. If you click it, a windows dialog will popup, this can not be handled by selenium.

 /*This is the WebDriver object used to manipulate web browsers.*/
 WebDriver driver;
 /*This page displays upload file web element, 
 * this is just a fake one. You can specify your real page.*/
 String uploadFileDisplayUrl = "";
 //Initialize the WebDriver object use FirefoxDriver.
 driver = new FirefoxDriver();
 //Use Firefox web browser to load and display the upload file page.
 //Get the upload file web element by it's name "uploadFileInputBox"
 WebElement element = driver.findElement("uploadFileInputBox"));
 //Input the uploaded file's absolute path as string use sendKeys() method.
 //Find the submit button in the web page and click it to upload. 
 //Get the return message in the returned web page. 
 String checkText = driver.findElement("returnMessage")).getText();
 //Check whether the upload action success or fail by verify the return message.
 Assert.assertEquals("The upload process has been completed successful", checkText);

[download id=”505″]

0 0 vote
Article Rating
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x