Here I would like to share my experience on handling file upload using selenium. Handling File upload with selenium I spent more than two days and googled many sites to overcom this. At last I was able to crack this and found solution for the same. This script is devledoped in Java and can be easily coverted to any other langugage. 

To handle file upload using selenium RC (1.0 or higher) comes with two challenges.

1. Clicking on Browse/Upload button. ( As Upload buttion come with input type File which is combination of both text box and Browse button).

2. Selecting a file from windows dialog.

I will share handling this on both Fire fox and IE.

Handling file upload in Fire Fox:


Its really very simple when comes to handle file upload in Fire Fox. You just need to use selenium.type command for input file=type control.

Lets take below sample html code.

All you just need to do is use below command to upload file.

selenium.type("//input[@name='fileupload']","c:\test.txt")

Type command take care of uploading file automatically. No other code is required to handle this.


IE:


When it comes to IE its little tricky. Follow below steps.

1. Download AutoIt latest version.
2. Open new editor and past below code in editor.

If $CmdLine[0]<2 Then
Exit
EndIf


handleUpload($CmdLine[1],$CmdLine[2])


;define function to handleupload


Func handleUpload($title, $uploadFile)


if WinWait($title,"",4) Then
WinActivate($title)
ControlSetText($title,"","Edit1",$uploadFile) ;put file path into text fild
ControlClick($title,"","Button2")
Else
Return False
EndIf

EndFunc

4. Go to Tools menu click on build the code. It will generate an .exe (e.g. upload.exe)
5. Now write a function in java to make a call to aboe auto it function. Below is sample code for the same.

public void handleUpload(String windowtitle, String filepath) {
         String execute_file = "upload.exe";
         String cmd = "\"" + execute_file + "\"" + " " + "\"" + windowtitle + "\""
                                   + " " + "\"" + filepath + "\""; //with arguments
         try {
                 Process p = Runtime.getRuntime().exec(cmd);
                
         } catch (Exception e) {
                 e.printStackTrace();
         }

}


6. In you TC first call above java function ( remember first you need to call function before click on browse button. Else control never comes back to your code if you click browse button first.

7. Now click on upload button using selenium.click("//input[@name='fileupload']").


In other browsers like chrome and safari I tired either type or AutoIt code will function successfully. 

 

{jcomments on}


Like it on Facebook, Tweet it or share this article on other bookmarking websites.

No comments