How to Upload File using Selenium

As an automation tester, one of the crucial tasks is to upload files and validate the file upload functionality of a website. Upload file using Selenium WebDriver is an essential task that can save a lot of time and effort for testers.

In this blog, I will guide you through the step-by-step process of uploading files using Selenium WebDriver and Java programming language.

Prerequisites for Performing Functionality of Upload File using Selenium

  1. Selenium WebDriver:
    You must have Selenium WebDriver installed on your system. You can download the latest version of Selenium WebDriver from the official Selenium https://www.selenium.dev/downloads/ website.
  2. Programming Language:
    In this blog, I will be using Java programming language to write the code. Therefore, you must have a basic understanding of Java syntax and programming concepts.
  3. Web Browser:
    You must have a web browser installed on your system that is supported by Selenium WebDriver. Selenium supports different web browsers, including Chrome, Firefox, Safari, and Edge.
  4. File to Upload:
    In this Blog, I will be using a simple file to upload to a website.

Methods to Upload File using Selenium

There will be having different methods that can be used to perform the functionality of Upload File using selenium:

1. Upload File using SendKeys Method

The sendKeys method is one of the easiest method to perform the functionality of upload file using Selenium. It allows you to perform typing in a text area field or upload a file by specifying the path of the file you want to upload.

You can use following steps to upload a file using sendkeys method:

I. Find the file input element:
you can use a unique identifier like as an ID, class name, or name property to locate the file input element on the web page. For locating them you can use different Web locators(Check our detailed blog on Web Locators).
Syntax:

WebElement fileInput = driver.findElement(By.id("file-upload"));

II. Specify the file path:
Once you have located the file input element using any of the web locator, you can then use the sendKeys method to specify the path of the file you want to upload.
Syntax:

fileInput.sendKeys("C:\\path\\to\\file.txt");

The sendKeys method sends the file path as if you were typing it into the file input element. The file path should be a string that represents the full path to the file you want to upload, including the file name and extension.

III. Submit the form:
Once you have specified the file path, you can submit the form to upload the file.
Syntax:

driver.findElement(By.id("file-submit")).click();

Programmatic Demonstration of Upload File using SendKeys Method

I will be using https://the-internet.herokuapp.com/upload website for a practical demonstration of all the methods:

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

public class SendKeysexample {

	public static void main(String[] args) {

		// Create a new instance of the ChromeDriver
		WebDriver driver = new ChromeDriver();

		// Navigate to the website
		driver.get("https://the-internet.herokuapp.com/upload");

		// Find the file input element by ID
		WebElement fileInput = driver.findElement(By.id("file-upload"));

		// Enter the file path to upload using sendKeys method
		fileInput.sendKeys("D:\\Testingmint.txt");

		// Find and click the Upload button
		WebElement uploadButton = driver.findElement(By.id("file-submit"));
		uploadButton.click();

		// Wait for the upload to complete and verify the success message
		WebElement successMessage = driver.findElement(By.tagName("h3"));
		String message = successMessage.getText();
		if (message.contains("File Uploaded!")) {
			System.out.println("File uploaded successfully!");
		} else {
			System.out.println("File upload failed!");
		}

		String Filename = driver.findElement(By.id("uploaded-files")).getText();
		System.out.println(Filename);
	}

}

2. Upload File using Robot Class

Robot class is a part of the Java AWT (Abstract Window Toolkit) package. It can be used to perform keyboard and mouse actions. You can use Robot class to navigate to the file upload window, select file, and click Open button.

You can use following steps to upload a file using Robot Class:

I. Find the file input element:
you can use a unique identifier like as an ID, class name, or name property to locate the file input element on the web page. For locating them you can use different Web locators(Check our detailed blog on Web Locators).
Syntax:

WebElement fileInput = driver.findElement(By.id("file-upload"));

II. Click the file input element:
Once you have located the file input element, you can use click() method with moveToElement() method of Actions class to click the element and open file upload window.
Syntax:

Actions action = new Actions(driver);
action.moveToElement(fileInput).click().perform();

III. Create Robot Class instance:
You have to create an instance of the Robot class to perform keyboard actions.
Syntax:

Robot robot = new Robot();

IV. Set delay time:
You have to set a delay time to allow the file upload window to open.
Syntax:

robot.delay(2000);

V. Set the file path:
You can use the StringSelection and Toolkit classes to copy the file path to the clipboard.
Syntax:

StringSelection stringSelection = new StringSelection("C:\\path\\to\\file.txt");
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);

VI. Perform keyboard events:
You can use the Robot class to Perform keyboard events to navigate to the file upload window, paste the file path, and select the file.

Following are keyboard events that used to perform upload file using Robot Class:

  • robot.keyPress(KeyEvent.VK_CONTROL):
    It is used to perform the pressing of the “Control” key on the keyboard.
  • robot.keyPress(KeyEvent.VK_V):
    It is used to perform the pressing of the “V” key on the keyboard.
  • robot.keyRelease(KeyEvent.VK_CONTROL):
    It is used to perform the Release of the “Control” key on the keyboard.
  • robot.keyRelease(KeyEvent.VK_V):
    It is used to perform the Release of the “V” key on the keyboard
  • robot.keyPress(KeyEvent.VK_ENTER):
    It is used to perform the pressing of the “Enter” key on the keyboard
  • robot.keyRelease(KeyEvent.VK_ENTER):
    It is used to perform the Release of the “Enter” key on the keyboard

Syntax:

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

VII. Submit the form:
Once you have selected the file, you can submit the form to upload a file.
Syntax:

driver.findElement(By.id("file-submit")).click();

Programmatic Demonstration of Upload File using Robot Class

import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.event.KeyEvent;
import java.io.IOException;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;

public class Robotclassexample {

	public static void main(String[] args) throws AWTException, IOException, InterruptedException {

		// Create a new instance of the ChromeDriver
		WebDriver driver = new ChromeDriver();
		driver.manage().window().maximize();

		// Navigate to the website
		driver.get("https://the-internet.herokuapp.com/upload");

		// Find the file input element by ID
		WebElement fileInput = driver.findElement(By.id("file-upload"));

		// Click the file
		Actions action = new Actions(driver);
		action.moveToElement(fileInput).click().perform();

		// Create a new Robot instance to handle the file chooser dialog
		Robot robot = new Robot();
		robot.delay(2000);

		// Set the file path to upload to the clipboard
		StringSelection filePath = new StringSelection("D:\\Testingmint.txt");
		Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
		clipboard.setContents(filePath, null);

		// Simulate key presses to navigate to the file input field and paste the file
		// path from the clipboard
		robot.keyPress(KeyEvent.VK_CONTROL);
		robot.keyPress(KeyEvent.VK_V);

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

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

		// Find and click the Upload button
		WebElement uploadButton = driver.findElement(By.id("file-submit"));
		uploadButton.click();

		// Wait for the upload to complete and verify the success message
		WebElement successMessage = driver.findElement(By.tagName("h3"));
		String message = successMessage.getText();
		if (message.contains("File Uploaded!")) {
			System.out.println("File uploaded successfully!");
		} else {
			System.out.println("File upload failed!");
		}

		String Filename = driver.findElement(By.id("uploaded-files")).getText();
		System.out.println(Filename);
	}

}

3. Upload File using AutoIT Tool

AutoIT is a third party tool that can be used to automate Windows GUI and general scripting tasks. You can use AutoIT to navigate to the file upload window, select file, and click Open button.

You can use following steps to upload a file using AutoIT tool:

I. Download and install AutoIT:
You first need to download and install the AutoIT tool on your system. You can download it from the official website (https://www.autoitscript.com/site/autoit/downloads/).

II. Write AutoIT script:
You can create an AutoIT script using the SciTE Script Editor that comes with AutoIT.
Syntax:

ControlFocus("Open","","Edit1")
ControlSetText("Open","","Edit1","C:\path\to\file.txt")
ControlClick("Open","","Button1")

III. Compile the AutoIT script:
Use the following steps to compile the AutoIT Script:

  1. Go to the directory where the file is saved
  2. Right Click on the file
  3. Based on your machine choose the compile option, i.e compile script x64 OR compile script x86
compile AutoIT script

IV. Execute the AutoIT executable(.exe) file:
After compiling the AutoIT script, you can use the Runtime class in Java to execute the AutoIT executable.
Syntax:

Runtime.getRuntime().exec("C:\\path\\to\\upload.exe");

V. Submit the form:
Once you have selected the file, you can submit the form to upload a file.
Syntax:

driver.findElement(By.id("file-submit")).click();

Programmatic Demonstration of Upload File using AutoIT Tool

import java.io.IOException;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;

public class AutoITexample {

	public static void main(String[] args) throws IOException, InterruptedException {

		// Create a new instance of the ChromeDriver
		WebDriver driver = new ChromeDriver();

		// Navigate to the website
		driver.get("https://the-internet.herokuapp.com/upload");

		// Find the file input element by ID
		WebElement fileInput = driver.findElement(By.id("file-upload"));

		// Click the file
		Actions action = new Actions(driver);
		action.moveToElement(fileInput).click().perform();
		Thread.sleep(2000);

		// Call the AutoIT script to handle the file chooser dialog
		Runtime.getRuntime().exec("D:\\Fileupload.exe");

		// Find and click the Upload button
		WebElement uploadButton = driver.findElement(By.id("file-submit"));
		uploadButton.click();

		// Wait for the upload to complete and verify the success message
		WebElement successessage = driver.findElement(By.tagName("h3"));
		String message = successMessage.getText();
		if (message.contains("File Uploaded!")) {
			System.out.println("File uploaded successfully!");
		} else {
			System.out.println("File upload failed!");
		}
	}
}

Scenarios of Upload File

  • E-commerce websites:
    Online shopping websites allow customers to upload images of their products, such as when ordering custom-made goods.
  • Job application portals:
    When applying for jobs online, job seekers are often required to upload their resumes and cover letters.
  • File sharing websites:
    Websites that allow users to share files with each other, such as cloud storage services, often require users to manually upload files.
  • Online education portals:
    Online education platforms often require students to upload assignments, projects, and other course materials.

Overall, automating file upload can be useful in any situation where files need to be uploaded frequently or as part of a larger automated process.

Conclusion

In Conclusion, automating the functionality of Upload file using Selenium can be a time-saving and efficient solution for many scenarios where web applications used this functionality.

You Might Like: