Friday, February 25, 2011

Selenium - File Upload/Download using Autoit

Selenium - File Upload/Download using Autoit


I was working on selenium scripts and came across file upload functionality. Selenium core JavaScript engine don't have capability to handle the windows pop-up due to same origin policy, so we need to relay on other tools. One of the best open source tool for handling windows objects is Autoit. Lets understand how to use this tool for the functionality that can't be handled by the selenium.


I would like to explain the Autoit tool on the file upload functionality. Download the tool form the above mentioned site, create the appropriate Autoit script, compile into exe file, test the exe file to verify whether the functionality is working as expected and integrate with selenium. Read the help file for better understanding.


I have web button on the page, when selected, browser opens the following window(attaching screen shot below). Selenium works fine till this button selection, now it is the responsibility of the Autoit script to select the file so that selenium can continue with the remaining GUI activity.




What are the different steps that need to be performed by the Autoit to select the file from the above window.
1. Select the window and get the focus on it.
2. Type the file name with path in the text box.
3. Select open button, so that all the selection details are transfered into web page control and selenium can take control of the next activity.


Following is the Autoit script for the above steps, compile and convert into exe file and call from selenium. How to call the exe file from JAVA?
Java Code
Runtime.getRuntime().exec("C:\\NEW.EXE " + FileName); //call Autoit script with one parameter FileName
AutoIt Script
;MsgBox(0,"Parameters",$CmdLine[1]) ;Sending parameters through command line
FileCopy("C:\W3C.png", "C:\"&$CmdLine[1]&".png") ;Make a duplicate copy of the file, as same file name is not accepted
sleep(3000);delay for 3 seconds for the file to create
WinWaitActive("#32770", "Choose File to Upload",10)
WinFlash("Choose File to Upload","", 4, 500) ; Just to Flash the window
ControlSetText("Choose File to Upload", "", "[CLASS:Edit; INSTANCE:1]", "C:\"&$CmdLine[1]&".png")
ControlClick("Choose File to Upload", "","[CLASS:Button; INSTANCE:2]");

How to capture the Windows object properties, by using Autoit Windows Info tool, following screen shot demonstrates how to open and capture the windows controls.


Drag and drop the finder tool icon on the windows objects to get its corresponding properties.
Verify help to understand the syntax of Autoit commands. 



Enjoy scripting Autoit...cool tool.

--- 

27 comments:

  1. What about when we want to upload files one by one using one exe.?

    ReplyDelete
  2. Manish, In the above code you can pass the file name to the exe file and upload any number of files.

    ReplyDelete
    Replies
    1. Hi Bharath,

      I am using the below java code to upload multiple files using AutoIt but first file is getting replaced with first file.
      Can we upload 3 or more files at a time without getting replaced or is there any code for pressing ctrl+A and selecting files?

      public String uploadUsingAutoIt(String object,String data) throws IOException
      {
      try {ProcessBuilder p = null;
      List path_file=new ArrayList();
      driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
      String currDir = System.getProperty("user.dir");
      String sep = System.getProperty("file.separator");
      String temp[] = data.split(",");
      String obj[]=temp[1].split(" ");
      String path_exe = currDir + sep + "externalFiles" + sep + "uploadFiles"+ sep + temp[0].trim();
      for(int i=0;i<obj.length;i++)
      {
      String path = currDir + sep + "externalFiles" + sep + "uploadFiles"+ sep + obj[i].trim();
      path_file.add(path);

      }
      for(int k=0;k<path_file.size();k++){
      p=new ProcessBuilder(path_exe,path_file.get(k), "Open");
      }
      p.start();
      }
      catch (Exception e) {
      return Constants.KEYWORD_FAIL + " Unable to upload "
      + e.getLocalizedMessage();
      }
      return Constants.KEYWORD_PASS+ "File/Video Uploaded sucessfully.";
      }

      Please help me on this issue.

      Thanks,
      Anil Reddy.
      anil.reddy5153@gmail.com.

      Delete
  3. You may want to look at Sikuli.org (the Java API), a cross-platform solution to do what you can do with AutoIt on Windows.

    ReplyDelete
  4. Hi Bharath,
    How can we pass different file names to exe file. Because we are saving the file only once initially. Actually i need to pass file names dynamically, so it has to change continously, at that time how can i pass the file names. Please help me.

    ReplyDelete
    Replies
    1. Using command line parameters, it is captured in $CmdLine[1]. In the above example I am passing filename.

      Delete
  5. How can we update perticular cell in excel sheet using jdbc odbc connections.Here i am sending my code check this.
    import java.io.IOException;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import jxl.write.WriteException;
    import jxl.write.biff.RowsExceededException;
    public class reading_excel {

    public static void main(String[] args) throws ClassNotFoundException, SQLException, IOException, RowsExceededException, WriteException, InterruptedException
    {
    Connection conn = null;
    Statement stmnt = null;
    Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
    conn = DriverManager.getConnection( "jdbc:odbc:Driver={Microsoft Excel Driver (*.xls)};DBQ=C:/Documents and Settings/nn/Desktop/New1.xls");
    stmnt = conn1.createStatement();
    String query1 = "update [Sheet1$] set Status =updated where FirstName=abc;";

    stmnt.executeUpdate(query1);
    System.out.println("query updated");


    stmnt.close();
    conn.close();
    }}

    The above script giving following error.
    [Microsoft][ODBC Excel Driver] Operation must use an updateable query
    Please send me some examples on this.
    Thanks
    Manohar

    ReplyDelete
    Replies
    1. This link may help u
      http://bharath-marrivada.blogspot.in/2011/07/selenium-testng-parameterization-excel.html

      Delete
  6. I found this quite interesting today of all days.

    I just finished using AutoIt to do almost the same thing with EAFUploader ( flash object uploader ).
    I had to get the dialog handle, control handles, etc ( I did a bit more like navigating to photo folder, selecting specific photos, verifying ). I also used AutoIt to hook the flash object events for uploading so I could monitor status, so as you've found, AutoIt is very powerful for windows automation and other needs.

    One thing... Your AutoIt assumes that your Java code escaped any spaced strings... I don't know Java directly, but I don't see "FileName" escaped. Could lead to issues. Also, your code implies by specifically using $Cmdline[1] that there was actually a length string passed, if something should go wrong, and that FileName is actually empty, you'll get an AutoIt error exception.

    I find all of this interesting, I'd never heard of Selenium before today. I've always used AutoIt to test and automate websites directly, heck, even used AutoIt as server side code to run a few sites ( like php ) in the past.

    Anyway, thanks.
    - SmOke_N

    ReplyDelete
    Replies
    1. I perform all the validations in Java and make sure proper file name is passed. I don't want to put complex validation in Autoit, if some thing goes wrong hardly one test case would get failed. Most of the web application is handled using Selenium, but there are limitations where in we use Autoit just for that step only.

      Delete
    2. Very good. Like I said, you've used it as many others do, opportunity outside the means or within the means but avoiding long drawn out code.

      Regards,
      - SmOke_N

      Delete
  7. Hi Bharath

    I have used auto it to upload the files in webdriver on windows-xp, it is running fine. Then i am trying to run same script on windows7 machine it is giving error(Error opening the destination file)while compile autoit script. I have changed all paths even thow it is giving that error, please help me. Is there any compatibility issue while moving to windos7.

    ReplyDelete
    Replies
    1. I think for windows 7 you need to create a new exe file by selecting appropriate settings during compilation.

      Delete
  8. Hi Bharath

    I have used auto it to upload the files in webdriver on windows-xp, it is running fine. Then i am trying to run same script on windows7 machine it is giving error(Error opening the destination file)while compile autoit script. I have changed all paths even thow it is giving that error, please help me. Is there any compatibility issue while moving to windos7.

    ReplyDelete
  9. Hi Kodalikmr,
    You need to create the .exe file using compile x64 option available if the operating system is of type x64 architecture[64 bit architecture].

    ReplyDelete
  10. Hi,
    In my project i have a requirement to upload a file. I could do it by creating AutoIt script and calling it from selenium. Now the problem is i need to parameterize the file path in AutoIt script. Because for now i am hardcoding the filepath for which i need to upload. In case if this script has to run in other machines, they should keep the file in the same place to run. Is there anyway that i can resolve this issue?

    ReplyDelete
    Replies
    1. yes. All the command line parameters are store in the following variables $CmdLine[1]....
      This is already explained above, just go through the content again.

      Delete
  11. how to upload multi files in sigle shot in open dialog box

    ReplyDelete
  12. If in run my script in firefox its working fine.Same script I run IE flickering Problem arises,can any body help me out.Iam using IE version8 with drivers IEDriverServer

    ReplyDelete
  13. Hi Bharath,

    I want to download a file using selenium web driver framework. so help how to download file code work?

    ReplyDelete
  14. Hi i am unable find code for download a file using selenium web driver

    ReplyDelete
  15. Hi Bharath,

    I want to download a file using selenium web driver framework. so help how to download file code work?
    please send link how to find code?

    Thanks,
    Anil

    ReplyDelete
  16. Hi Bharath,

    Even I am unable code to download the Excel file using Webdriver. Can you share the AutoIT code for downloading the Excel file.

    Thanks
    Mahesh

    ReplyDelete
  17. Hi Anil Kumar,

    Did you get the solution for download file code. if you find can you share it with me.

    Thanks in Advance,
    Mahesh

    ReplyDelete
  18. Hi guys i am facing problem with autoit while uploading the photo using selenium,and the prob is i can able to upload the pic only once and when i try to run the selenium script again its not uploading the file (its not locating the file location) please help guys
    thanks in advance
    mahesh sk

    ReplyDelete
  19. Hi Bharath,

    I am trying to upload a file but it will not work, below is my webdriver code and AutoIT code

    Webdriver script-

    package day1;

    import java.util.concurrent.TimeUnit;

    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.chrome.ChromeDriver;

    public class autoIT {

    public static void main(String[] args) {
    try
    {
    String filename= "E:\\testCaseSheet.xls";

    System.setProperty("webdriver.chrome.driver", "C:\\Users\\xyz\\Downloads\\chromedriver.exe");
    WebDriver driver = new ChromeDriver();
    driver.manage().window().maximize();
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

    driver.get("http://www.toolsqa.com/automation-practice-form");

    driver.findElement(By.id("photo")).click();
    //Thread.sleep(5000);
    Runtime.getRuntime().exec("E:\\fileupload.exe" + filename);
    Thread.sleep(5000);

    }
    catch(Exception e)
    {
    e.printStackTrace();
    }

    }

    }


    Auto IT script-

    Sleep(2000)
    ControlFocus("File Upload","","Edit1")
    Sleep(2000)
    ControlSetText("File Upload", "", "Edit1", "E:\testCaseSheet.xls")
    ControlClick("File Upload", "","Button1");


    could you please help me....

    ReplyDelete