How To Upload File Use Selenium WebDriver

Problem
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.

Solution
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">

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

</form>

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 = "http://www.dev2qa.com/demo/upload/uploadFileTest.html";
 
 //Initialize the WebDriver object use FirefoxDriver.
 driver = new FirefoxDriver();
 
 //Use Firefox web browser to load and display the upload file page.
 driver.get(uploadFileDisplayUrl);
 
 //Get the upload file web element by it's name "uploadFileInputBox"
 WebElement element = driver.findElement(By.name("uploadFileInputBox"));
 
 //Input the uploaded file's absolute path as string use sendKeys() method.
 element.sendKeys("C:/Workspace/uploadFileTest.txt");
 
 //Find the submit button in the web page and click it to upload. 
 driver.findElement(By.name("uploadFileSubmitBtn")).click();
 
 //Get the return message in the returned web page. 
 String checkText = driver.findElement(By.id("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 “TestUploadFile.zip” TestUploadFile.zip – Downloaded 76 times – 845 B

(Visited 1,321 times, 1 visits today)
READ :   Use TestNG To Run Selenium Test Scripts In Parallel Example

Leave a Reply

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

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