Advance Selenium

Upload file in Selenium webdriver using Robot class

Hello, Welcome to Selenium tutorials in this post we will see how to upload files in Selenium Webdriver using Robot class.

When you start automating web applications then you will get many scenarios where you need to upload a single file or multiple files in order to continue the flow.

If you click on file upload then the filer uploader model will appear which will ask to upload a file. The file uploader is windows control which Selenium cant handle so we need to take the help of another library or approach.

 

Upload file in Selenium Webdriver using Robot Class

Upload file in Selenium using robot class

There are multiple ways to upload files in Selenium Webdriver

  • You can directly use the sendKeys(“File path”) method but sometimes this method does not work. If the file uploader does not include an input tag.
  • We can use the Robot class to upload files in Selenium, which we will discuss today.
  • You can also take the help of Sikuli or a Robot class.

If you are new to Selenium and not aware of Robot class then check the below article which will describe you about robot class

Robot class in Selenium Webdriver

 

  • We can upload files using AutoIT as well.

 

 

Robot class is not part of Selenium it comes with Java but we can use the same here. We have to use some keyboard events to perform this.
Step 1- We have to copy the file location in the system clipboard.
Step 2- We have to click on the upload button and use CTR+V and ENTER.
Note- Robot class each key has to press and release respectively

Scenario-
1-Open Firefox and Create a profile in monster.com
2- Click on the upload button and select the file and save
Lets implement the same

 

Program-Upload file in Selenium Webdriver using Robot Class

import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;
import java.awt.*;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;

public class FileUpload {
 
@Test
public void Fileupload() throws AWTException, InterruptedException{
 

// Start browser
 WebDriver driver = new FirefoxDriver();

// maximize browser
 driver.manage().window().maximize();
        
  // Specify the file location with extension
 StringSelection sel = new StringSelection("C:\\Users\\Desktop\\1.doc");

   // Copy to clipboard
 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(sel,null);
 System.out.println("selection" +sel);
 

// Open Monster.com
 driver.get("http://my.monsterindia.com/create_account.html");
 Thread.sleep(2000);

 // This will scroll down the page 
 JavascriptExecutor js = (JavascriptExecutor)driver;
 js.executeScript("scroll(0,350)");

// Wait for 5 seconds
 Thread.sleep(5000);

// This will click on Browse button
 driver.findElement(By.id("wordresume")).click();



 System.out.println("Browse button clicked");

 // Create object of Robot class
 Robot robot = new Robot();
 Thread.sleep(1000);
      
  // Press Enter
 robot.keyPress(KeyEvent.VK_ENTER);

// Release Enter
 robot.keyRelease(KeyEvent.VK_ENTER);

  // Press CTRL+V
 robot.keyPress(KeyEvent.VK_CONTROL);
 robot.keyPress(KeyEvent.VK_V);

// Release CTRL+V
 robot.keyRelease(KeyEvent.VK_CONTROL);
 robot.keyRelease(KeyEvent.VK_V);
 Thread.sleep(1000);
        
         Press Enter 
 robot.keyPress(KeyEvent.VK_ENTER);
 robot.keyRelease(KeyEvent.VK_ENTER);

}

}

 

Please comment below you are facing any issue while uploading the file

Now if you are comfortable with Basic Selenium, you can check out Advance Selenium Tutorial as well. ?

For More updates Learn Automation page

For any query join Selenium group- Selenium Group

author-avatar

About Mukesh Otwani

I am Mukesh Otwani working professional in a beautiful city Bangalore India. I completed by BE from RGPV university Bhopal. I have passion towards automation testing since couple of years I started with Selenium then I got chance to work with other tools like Maven, Ant, Git, GitHub, Jenkins, Sikuli, Selenium Builder etc.

57 thoughts on “Upload file in Selenium webdriver using Robot class

  1. Anjali says:

    I uploaded file using Sendkeys and it’s working fine. But in actual UI the upload button is not working due to some issues in UI, still when I run the script the file is getting uploaded from the path I had given in sendkeys. As per my script it should fail if the button is not working. Don’t know why its happening. Any solution? I’m using window 10

    1. Hi Anjali,

      This is one of the bugs with the upload scenario which you have found. I would recommend you to use AutoIT https://vistasadprojects.com/mukeshotwani-blogs-v2/upload-file-in-selenium-webdriver-using-autoit/

  2. Ashi says:

    How can i achieve file upload using Robot class in python

    1. Hi Ashi,
      You can use pyautogui for file upload.

  3. Anil Rautela says:

    Hi Mukesh,

    I am trying to attach file/files in Gmail on win10 chrome and nothing is happening using robot class. below is my code:

    ========================

    // Path Selection
    StringSelection sel=new StringSelection(” D:\\Automation\\program.txt”);
    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(sel, null);
    System.out.println(“Selection” +sel);

    // Attachments
    driver.findElement(By.id(“:1br”)).click();
    Robot robot=new Robot();
    robot.keyPress(KeyEvent.VK_ENTER);
    robot.keyRelease(KeyEvent.VK_ENTER);

    robot.keyPress(KeyEvent.VK_CONTROL);
    robot.keyPress(KeyEvent.VK_V);

    robot.keyRelease(KeyEvent.VK_CONTROL);
    robot.keyRelease(KeyEvent.VK_V);

    Thread.sleep(1000);

    robot.keyPress(KeyEvent.VK_ENTER);
    robot.keyRelease(KeyEvent.VK_ENTER);

    ========================

    Could you please share the workaround.

    1. Hi Anil,

      If you are Win 10 machine then I would recommend you to use AutoIT and here is link for your ready reference https://vistasadprojects.com/mukeshotwani-blogs-v2/upload-multiple-files-in-selenium-webdriver/

  4. Kathirvel says:

    Hi Mukesh, When I pass file location as a parameter (say x:\hello\file.png) , mouse action goes away from window folder and clicks somewhere else. At the same time, If I hard code the file name (say name = test + “file.png”) then this code perfectly works.

    Any help pls?

    1. Hi Kathirvel,

      On windows pop up for file upload, mouse hover actions from Selenium never works. If you are using AutoIT mouse hover action then it will work. And if you are doing this using tab keys followed by pasting file path.
      Please explain how your file path stuffs are not working.

  5. Petrishiya says:

    Hi Mukesh,

    I am getting file not found error though the file is in the given path and i have given the entire path name also.What are the possible solutions

    1. Hi Petrishiya,

      Are you getting this error message on file upload window, if so then kindly check absolute file path once again(file extension also to be included in file path)

  6. Satya says:

    Hi Mukesh,

    I am facing problem as for uploading file .Here there has no attribute like “type=’file'” and developer user ” type=’button'” .For this i used robot class with same approach as mentioned above.But the problem is
    sometime it is working fine late once or twice but then it is not uploading file .So what could be the best
    possible approach so that it will never fail .

    Thanks in advance.

    Ragards,
    Satya

    1. Hi Satya,

      Robot class for file uploading is just a workaround. Yuu should use AutoIT to complete your requirement, please refer this link https://vistasadprojects.com/mukeshotwani-blogs-v2/upload-multiple-files-in-selenium-webdriver/

  7. Roman Glaz says:

    Hi Mukesh,

    Your solution working well for me in chrome with (non-headless mode) , but not working with headless mode (do you have a solution for that ?)

    1. Hi Roman,

      Robot class implements virtual keyboard events which won’t work in headless mode. I would recommend you use AutoIt if you are working on Windows platform.

  8. Akash Rawat says:

    Hi Mukesh,

    I followed the same steps to create the HTML file but I didn’t get the Browse button. Instead I’m getting a text box.

    Please help.

    1. Hi Akash,

      Have you tried this input type=”file” name=”fileToUpload” inside tag ?

      1. Akash Rawat says:

        Nope. How should I use this?

  9. Ramya says:

    I tried with robot class in mac, I could see the path opened but could not select the file to upload.I’m stuck here.Can you please suggest me on this.

  10. Lijesh says:

    Hi Mukesh,
    Is there any way to get which browser is used for selenium test in AutoIT. For example, title of file upload window is different from browser to browser (“File Upload” for firefox and “Open” for Chrome). So I would like to use a single AutoIT script to handle both the case. If we get the browser name in AutoIT on run time, then we can handle it seamlessly for all browser.

    Thanks in Advance,
    Lijesh E M

    1. Hi Lijesh,

      We use 3 autoit script. So whenever we have cross browser we check first if browser is equal to FF then call script and so on.

  11. Vacha says:

    Hey mukesh..great post..
    Can we some workaround of autoIT for mac ?

    Thanks in advance

    1. Hi Vacha,

      There are other tools such as atomac which automates GUI based operation on Mac but you should know python programming or you can give a try to Sikuli. For more details on Sikuli, kindly check this post https://vistasadprojects.com/mukeshotwani-blogs-v2/integrate-sikuli-with-selenium-webdriver/

  12. Shubham says:

    Hi Mukesh, thanx for the video, but when I tried to upload file using AutoIT in my Windows 10 laptop , the window gets opened up for browsing but it is getting stuck there and getting failed. I tried putting implicit wait and Thread.Sleep method but no change in the Result. Can you please help?

    1. Hi Shubham,

      Implicit and Explicit wait never works for OS based pop ups. Because these wait intends for webelements and web based locators. Please visit this link https://vistasadprojects.com/mukeshotwani-blogs-v2/upload-file-in-selenium-webdriver-using-autoit/ and use autoit script from this post. If after compilation it is not responding then try to compile same .au3 script using downgraded version of AutoIt tool.

  13. Sreedhar says:

    Hi Mukesh,

    Am trying to execute your code exactly but am getting the below error.

    Exception in thread “main” java.lang.Error: Unresolved compilation problems:
    VK_CONTROL cannot be resolved or is not a field
    VK_V cannot be resolved or is not a field
    VK_ENTER cannot be resolved or is not a field

    at Robot.main(Robot.java:61)

    Please help me.

    1. Hi Sreedhar,

      I guess you have imported wrong packages.

  14. praneeth says:

    Why do we need to use ENTER key release and key press, without we can proceed upload!:
    // Press Enter
     robot.keyPress(KeyEvent.VK_ENTER);

    // Release Enter
     robot.keyRelease(KeyEvent.VK_ENTER);

    1. Hi Praneeth,

      ENTER key only will press ok button for file submission.

  15. ganesh says:

    Hey, Mukesh Great tutorial but one problem i am facing is that I have used your code as it is but whats happening is the upload browser folder opens and then it just stuck there no progress.
    I am using ubuntu and giving path like “/home/user/Downloads/image.jpg”
    If u can help.

    1. I am not good n Linux so not sure Ganesh

  16. vinay says:

    i mukesh ,
    the above video belongs to autoit.but we need robot class video.please upload.

    1. Hi Vinay,

      For robot class i have to create video.

  17. Roma says:

    Hi,
    How to select multiple files at a time for uploading? Please suggest.

  18. BISHNU DAS says:

    Thanks for your above code, but my question is , why are you using Hard coded wait? can we use explicitly or implicitly wait instead of that?

    Thank you
    Bishnu Das

    1. Yes Bishnu you can use smart wait here

  19. Nikhil says:

    Mukesh how did find this default tookit and other functions. Its hard to find these tings I mean to get even an idea that such things exist.

    1. Hey Nikhil,

      🙂 it will come once you start exploring.

  20. sandip says:

    This code works perfectly fine. Thanks a lot Mukesh for this descriptive code 🙂

    1. Cheers Sandip. Keep learning.

  21. Reshma Sultana says:

    Hi Mukesh,

    The above upload file program works perfectly.But i have got one problem. While the monster page is opening, it shows another popup window and i can’t dismiss this window using alert command.Could you please help me?

    1. Manoj Kumar says:

      Hi Reshma

      Make sure whether it is an alert pop up or an window pop,If it is another window than it will not be closed by an alert command.Try this if it is an window pop up
      ArrayList wins= new ArrayList(driver.getWindowHandles());
      driver.switchTo.window((String)wins.get(1)).close();
      Thread.sleep(2000);
      driver.switchT0.window((String)wins.get(0));

      and then further proceed with your scripting

      1. Reshma Sultana says:

        The above code works fine. Thank you Manoj.

        1. Manoj Kumar says:

          Happy to help you 🙂

      2. Thanks Manoj with prompt reply

        1. Manoj Kumar says:

          Thank you sir its because of your tutorials only I am able to learn automation more clearly

  22. Suman says:

    Hi Mukesh,

    I am new to Selenium.Just one question.Why do we require to copy to clipboard?
    I tried doing doing it without using that code and that worked well(same code on monster.com itself).Please explain

    1. Hi Suman,

      Sometime default does not work so I always copy to clipBoard then apply robot class. 🙂 Hope its clear for u.

  23. Deepak says:

    Hi Mukesh,

    After pasting the path, KeyPress and KeyRelease for Enterkey is not closing the popup & script is getting failed.
    robot.keyRelease(KeyEvent.VK_CONTROL);
    robot.keyRelease(KeyEvent.VK_V);

    1. Hi Deepak,

      Try to give some wait between actions and it should work.

  24. Adilakshmi says:

    Hai mukesh
    This is Adilakshmi
    How to upload multiple files using autoit.

    1. You can use cmd line argument in AUtoit and then you can upload multiple files.

  25. Reshma says:

    I am unable to paste the path once the windows popup asks for upload file.Please suggest.

    1. Hi Reshma,

      Please use AutoIT to upload script this is more stable as compared to Robot class.

      Thanks
      Mukesh

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.