Uploading a file with Selenium Webdriver

There are different ways to handle file uploads with Selenium Webdriver.

The First and the Easy way is simple case of just finding the element and typing the absolute path of the document into it.

HTML code should look similar to this :

<input type="file" name="datafile">

Syntax:

//Find the element of upload button and send the path
WebElement element= driver.findElement(By.name("datafile"));
element.sendKeys("C:\Users\Easy\Desktop\testfile.txt");

Click here for example program

NOTE: This works only when the textbox is enabled. So please make sure that the input element is visible.

The OTHER WAY to Handle File Upload

What If there is no text box / input tag to send the file path using Sendkeys method????

You will have only a button (Customized button) and when click on browse button, browser opens a window popup and to select the file from windows, And as we know selenium will not support OS controls.

We can use AutoIt tool (open source tool) which takes the responsibility to upload the file.

About AutoIT : AutoIt v3 is a freeware BASIC-like scripting language designed for automating the Windows GUI and general scripting.

We need to call the AutoIt script after clicking on the upload button. Immediatly ater clicking on Upload button, the control should be transfered to AutoIt which takes care of uploading the file.

Syntax:

Runtime.getRuntime().exec("AutoIt .exe filepath");

Download and Install Autoit tool from Download AutoIt

Example:

Runtime.getRuntime().exec("D:/fileupload.exe");

Click here for example program

AutoIt script should have the following:

Step 1 : First After clicking on 'Upload' button, the cursor will move to the Window popup.

The below step should be the first line in the script. 'File Upload' is the name of the window popup when opened with Mozilla. The name changes depending on the browser.

Mozilla - File Upload
Chrome - Open
and for IE - Choose File to Upload

WinWaitActive("File Upload")

Step 2 : Once the window popup is active, we should send the path of the document which need to be uploaded.

 Send("Full path of the document")

Step 3 : After that we need to click on Open button which will upload the document.

Send("{ENTER}")
Selenium Tutorials: 

Comments

Thanks much for the simple and clear explanation.

Please help me to upload a file from my desktop through a eclipse for selenium. I tried a lot. But am getting an syntax error.

Error: UNDEFINED FOR THE TYPE BROWSETAB.

Hi, Really simple and useful information for Upload. I am looking for information on Downloading Files.... Can you please send some link if you have

Add new comment

Image CAPTCHA