How To Upload File Using Selenium Webdriver – 3 Methods

Learn different methods for handling file upload in Selenium with code examples:

File upload is performed when there is a need of uploading any file or a document on a specific website such as forms, registration pages, document uploaders, etc.

Uploading a file process includes browsing a file from the desired location or from your computer and uploading it to the website.

=> Check ALL Selenium Tutorials Here

Handling file upload in Selenium

Selenium Upload File

Handing file upload in Selenium can ease human work and can be done simply by using the sendKeys() method. A message is displayed after uploading a file that confirms if the file is being uploaded successfully. There are many more such automation methods for file upload.

Topics covered in this tutorial include file upload in HTML, methods for handling file upload in Selenium (which would include methods namely: using sendKeys, then using AutoIT and Robot class).

This tutorial also explains the implementation of code for handling file upload using these methods in Selenium, after which we will see a few examples where file upload is performed with the help of Selenium.

File Upload In HTML

The below code implementation explains file uploading operation on HTML Page. The HTML code shows how the upload operation can be performed by first clicking on the Choose File button to browse the file to be uploaded and then click on Upload File option, after which we can see the file is uploaded successfully.

html file upload

The above image consists of the HTML created page and below is the HTML code for the same. Let us give a quick look at the HTML code.


<title> File Upload </title>


<form action="photo_upload.png" method="post" enctype="multipart/form-data">
<h2> File Uploading (Upload the image file) </h2>
Select file to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload File" name="submit">



Thus on uploading the desired file by clicking the Upload File option, the below page (image) gets displayed (i.e. the uploaded image file is displayed) which confirms the file chosen to upload has been uploaded successfully.


[image source]

Methods To Upload Files In Selenium

Let us see some methods for Handling File Upload and also the implementation of code for the same.

Files uploading in Selenium can be done with the below methods:

  1. Using sendKeys method
  2. Using AutoIT tool
  3. With the help of Robot Class

#1) Using sendKeys method

The most basic way of uploading files in Selenium is using the sendKeys method. It is an inbuilt feature for file upload in Selenium.

The syntax is as below:

WebElement upload_file = driver.findElement(By.xpath("//input[@id='file_up']"));


Let us understand the code implementation for the above technique:

For uploading files using this method, we first need to inspect the element or the button provided for file upload, then by using sendKeys, browse the path where the actual file to be uploaded is kept. Place the path along with the file name in sendKeys so that the program is navigated to the mentioned path to fetch the file.

After this, click on the save or submit button and the file will be seen uploaded. At times, we also receive a message that the file is being uploaded successfully.

Code implementation using the sendKeys method:

package SeleniumPrograms;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class FileUpload {

   public static void main(String[] args) throws IOException, InterruptedException {
   // TODO Auto-generated method stub

   WebDriver d = new FirefoxDriver();
   d.manage().window().maximize(); //always write wait code after this
   d.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS); //for page load
   d.get(""); //Testing webpage
   d.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); //for Implicit wait

   JavascriptExecutor js = (JavascriptExecutor)d; //Scrolling using JavascriptExecutor
   js.executeScript("window.scrollBy(0,380)");//Scroll Down to file upload button (+ve)


   WebElement browse = d.findElement(By.xpath("//input[@id='file-upload']"));
   //click on ‘Choose file’ to upload the desired file
   browse.sendKeys("C:\\Users\\Chait\\Desktop\\Files\\Job Specification.txt"); //Uploading the file using sendKeys
   System.out.println("File is Uploaded Successfully");



Thus, for uploading files using the sendKeys option, we simply have to use the inbuilt sendKeys method to upload the required file successfully.


This is the output of the above code (for where we can see a message displayed as: “File uploaded successfully” on uploading the file in selenium web driver using sendKeys method.

#2) Using AutoIT

AutoIT is a freeware and an open-source automation tool for Windows operating system. It is written in a BASIC scripting computer language for automating the Microsoft Windows user interface. It simulates any combination of keystrokes, mouse movements, and windows control manipulation.

Steps to download and install the AutoIT tool:

  1. Open link
  2. Go to AUTOIT -> DOWNLOADS. Download the latest AutoIT.
  3. Proceed with AutoIT installation and setup (next -> agree -> 32/64 bit selection -> file installation location selection -> Finish.
  4. There are 2 setup files: a) AutoIt version 3 and b) SciTE autoit 3.
  5. After installation is done, open AutoIT editor.
  6. Go to the location where setup files are saved, click on ‘SciTE.exe’ file, and the AutoIT editor opens. Please see the below screenshot for AutoIT editor.



Now, let us understand in short how to use this tool:

  • Open the AutoIT editor.
  • We need to write a simple code in AutoIT editor, required for file upload operation (the name of the file to be uploaded, will be mentioned in the code).
  • Now close the editor and right click on it, you will see compile script option. Choose compile script (x64) option for 64 bit machine and go with compile script (x86) for a 32-bit machine.
  • As soon as the above step is completed, a .exe file is created and this file will be mentioned in our selenium eclipse code. After compilation, as seen the below image ‘fileupload.exe’ file gets created. Now we can make use of this file in the Selenium web driver script.



The below image helps us understand how the file to be uploaded that is form.csv is being uploaded by executing the selenium eclipse script which runs fileupload.exe file.

>> Visit this page for more details on AutoIT.


We will see the implementation of this method later in this tutorial.

Advantages of AutoIT:

  • AutoIT is an open-source tool for which we do not need to pay.
  • Small standalone executables can be created using AutoIT.
  • It supports easy to record or playback scripting.
  • We can debug the code easily with console write command.
  • It has the option to create different GUIs and recognizes almost all basic Windows controls.
  • It is simple and user-friendly.

Disadvantages of AutoIT:

  • It works only in Windows operating system
  • As fundamental coding principles knowledge is a must, it proves to be a great tool for professionals but might be a bit complicated for beginners.
  • AutoIT does not have Java support available so far.
  • The users need to import separate libraries while using different predefined utility functions.

Now, let us move to the implementation code of File Upload using AutoIT:

Here, we will see how we can handle file upload using AutoIT in Selenium. For this let us consider the example of OrangeHRM website.

Code implementation for handling file upload in Selenium using AutoIT:

package SeleniumPrograms;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class FileUpload {

  public static void main(String[] args) throws IOException, InterruptedException {
  // TODO Auto-generated method stub

   WebDriver d = new FirefoxDriver();
   d.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);    // for page load
   d.get(““);	      // Testing webpage
   d.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);      // for Implicit wait
   WebElement uname = d.findElement("txtUsername"));          // Username.........ID
   WebElement pwd = d.findElement("txtPassword"));	  // Password.........NAME
   WebElement loginb = d.findElement(By.xpath("//input[@id='btnLogin']"));;						             // Loginbutton......XPATH

   WebElement pim = d.findElement("menu_pim_viewPimModule"));;								            // Admin tab-PIM

   WebElement config = d.findElement("menu_pim_Configuration"));;							         //Configuration tab

    WebElement data_imp = d.findElement(By.partialLinkText("Data "));;				                  //Data Import tab.....PARTIALLINKT

    WebElement browser = d.findElement(By.xpath("//input[@id='pimCsvImport_csvFile']"));   //Browse button;								


  WebElement upload = d.findElement("btnSave"));	          //Upload button;
   System.out.println("File Uploaded Successfully");	       // Confirmation message


As seen in the above code, the following line is very important as it shows the use of AutoIT:



  • Runtime: It allows the script to interface with the environment in which the script is running.
  • getRuntime(): It is used to get the current runtime associated with the process.
  • exec(): It executes the AutoIT script (here, which is fileupload.exe).

When the program executes this line, it goes through the fileupload.exe file where the AutoIT code is executed as shown below:

ControlFocus("File Upload","","Edit1")
ControlSetText("File Upload","","Edit1","C:\Users\Chait\Desktop\autoit\data_file.csv")
ControlClick("File Upload","","Button1")


  • ControlFocus: This method sets the input focus to ‘file name’ text box.
  • ControlSetText: This method defines the path of the file. The file which we will be uploading in the ‘file name’ text box – its path is traced.
  • ControlClick: This method is used to click on the ‘Open’ button of the file uploader window.

The output for the above code is shown below:

Using AutoIT

[image source]

#3) With The Help Of Robot Class

Robots as we know, help in managing various activities such as performing some tasks, handling the keyboard functions, the mouse functions, and many more. Here we will understand certain functions that are helpful in controlling the keyboard and the mouse while an application is being tested using Selenium.

KeyEvents or Methods for implementing the Robot Class

In the implementation of Robot class, there are a few methods for the execution of test scripts.

These are mentioned below:

  • KeyPress(): This method is called when we want to press any key.
    • Example: robot.keyPress(KeyEvent.VK_ENTER);
  • KeyRelease(): This method is used to release the pressed key.
    • Example: robot.keyRelease(KeyEvent.VK_ENTER);
  • MouseMove(): Used when there is a need of moving the mouse pointer over ‘X’ and ‘Y’ coordinates.
    • Example: robot.mouseMove(coordinates.get.X(), coordinates.get.Y());
  • MousePress(): This method is called when we want to press the left mouse button.
    • Example: robot.mousePress(InputEvent.BUTTON_MASK);
  • MouseRelease(): This method is used to release the pressed mouse button.
    • Example: robot.mouseRelease(InputEvent.BUTTON_DOWN_MASK);

Advantages of Robot Class

  • File upload using the robot class is easy.
  • It handles the keyboard and mouse functions.
  • Handling pop-ups is also possible.

Disadvantages of Robot Class

  • Keyboard or mouse event would work only on the current instance of the window.
  • While executing a robot event, if the code execution is moved to another window, the mouse or keyboard event still remains on the previous window.
  • It is not easy to switch among different windows.

Implementation of code for File Upload using Robot Class:

For this, we will consider the example of the website. Below is the implementation code for handling file upload in Selenium using Robot class.

package SeleniumPrograms;

import java.awt.AWTException;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.util.concurrent.TimeUnit;
import java.awt.Robot;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;


public class FileUpload_Robo {

    public static void main(String[] args) throws InterruptedException, AWTException {
    // TODO Auto-generated method stub

    WebDriver drv = new FirefoxDriver(); // starting Firefox browser
    drv.manage().window().maximize(); // maximizing window
    drv.manage().timeouts().pageLoadTimeout(10, TimeUnit. SECONDS);//for page load
    drv.get("");//open testing website
    drv.manage().timeouts().implicitlyWait(10, TimeUnit. SECONDS);// for Implicit wait

    JavascriptExecutor js = (JavascriptExecutor)drv; // Scroll operation using Js Executor
    js.executeScript("window.scrollBy(0,200)"); // Scroll Down(+ve) upto browse option
    Thread.sleep(2000); // suspending execution for specified time period

     WebElement browse = drv.findElement(By.linkText("Upload a file"));
     // using linkText, to click on browse element; // Click on browse option on the webpage
    Thread.sleep(2000); // suspending execution for specified time period

    // creating object of Robot class
    Robot rb = new Robot();

    // copying File path to Clipboard
    StringSelection str = new StringSelection("C:\\Users\\Chait\\Desktop\\File upload.docx");
    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(str, null);

     // press Contol+V for pasting

    // release Contol+V for pasting

    // for pressing and releasing Enter


The output for the above selenium code is shown below:

plagiarism 1

Thus, files can be uploaded with the help of a Robot class, where we can see the use of input events like Key Pressing and Key Releasing for copying, pasting, entering, etc.

File Upload Examples

Let us see few examples of file upload which are performed with the help of Selenium:

#1) Gmail Account

In a Gmail account, while emailing someone, you can include an attachment i.e. a file document that might be of any type: doc, text, csv, image, pdf, etc. Here, file upload comes into context.

For more details please see below the screenshot of the file upload.


#2) Document upload for verification

Usually, for registration pages or forms, we need to upload documents for verification.

Please see the below image for more clarification:





For various such verifications such as proof verification, address verification, education proof, etc. specific documents need to be uploaded.


Thus, in this tutorial, we have seen file upload on the HTML page. We have also seen various methods for handling file upload in Selenium (which includes methods such as using sendKeys, using AutoIT, and using Robot class). We also understood the implementation of code for handling file upload in Selenium for each of these methods and finally looked at a few examples.

Author Bio– This article was written by Sonali Satpute, a qualified B.E.(Computer) from MITCOE, Pune, Professional Software Tester, and Content Writer.

=> Read Through The Complete Selenium Guide