How to upload and submit files using Selenium and AutoIt

Many web applications contain HTMML forms which interact with the user. The usser is able to enter data in to the form fields and submit the data to a server. Selenium is able to handle form inputs such as entering text in text fields, selecting a radio buttons, selectting a value from a drop-down menu and so on. Things get a little tricky when dealing with input form fields of type  " file ", to allow users to browse for a file and attach the file to the HTML form and submit the file.

So, what is the problem?

I can't seem to use selenium core to upload a file; when i try to type in the file upload text field, nothing happens!

Then seems to be two inter- related problems:

1. unfortunately, this is yet another javascript security restriction; JS is not allowed to modify the value of input type="file" form fields. You can work arround this by running your tests under selenium ide or under Selenium RC running in the experimental"*chrome" mode for firefox, but at present there is no stright forward away to do this in Selenium Core.

2. Handling of the "Choose File " dialogbox with selenium alone is not possible. We need to have another program running to select the path and file from the " Choose File " dialog box.

So, how can we upload file?

Fortunately, there exists a workarround the above problems. This is where the magic of AutoIt and selenium combination can work wonders!

First we will write a simple scipt in AutoIt and save the file as an executable:

1. WinWaitActive ("Choose File")

2. Send("c:\attach\samplefile.txt")  // location of the file you want to attach to the form and  submit

3. send("{enter}")

We shall name the above file as attachFile.exe

Now, within a java code we can run a process which will execute the above program just before when we want to upload and submit a file.

package com.company;

import java.io.*

import com.thoughtworks.selenium.Selenium;

public class AddAttachment

  {

    public static void attach(Selenium selenium,, String fileName);

      {

          try

             {

                    String[] commands = new String[]{};

                   Commands = new String[] {""c:\attach\samplefile.txt" };

                  Runtime.getRuntime().exec(commands);

              }

     catch(IO Exception e) { }

selenium.click("name = browseButton");

}

}

The above seems to be the easiest way to deal with file uploads and attachments using Selenium.