How to handle windows file upload using Selenium WebDriver?
Last Updated :
12 Sep, 2024
Handling file uploads in Selenium WebDriver is a common task in automation testing. In most web applications, uploading files is a critical feature that requires testing to ensure seamless functionality. Selenium WebDriver provides an easy and efficient way to automate file uploads. Unlike typical user interactions like clicks and text inputs, file upload automation in Selenium involves interacting with the file upload element, which can be handled directly using the sendKeys()
method.
Prerequisite
We will be required 3 main things:
- Java Development Kit (JDK) installed.
- Browser Driver (e.g., ChromeDriver for Chrome).
- IDE like Eclipse or IntelliJ IDEA.
Steps to handle windows file upload using Selenium WebDriver
The sendKeys method can be used to directly interact with the file input element in the web page. This method does not require any external tool. For this, the steps are given below
- Identify the file input element: First, we will find the input element on the page where the file needs to be uploaded.
- Use the sendKeys method: Then we will use the sendKeys method to input the file's absolute path to the file input element.
Dependencies
We will be required to have dependencies for selenium, for that, we will add dependencies in the XML file.
pom.xml
XML
<dependencies>
<!-- Selenium Java Dependency -->
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.21.0</version>
</dependency>
<!-- WebDriverManager Dependency -->
<dependency>
<groupId>io.github.bonigarcia</groupId>
<artifactId>webdrivermanager</artifactId>
<version>5.5.1</version>
</dependency>
<!-- TestNG Dependency (optional, if you're using TestNG) -->
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.8.0</version>
<scope>test</scope>
</dependency>
</dependencies>
Example
Index.html
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>File Upload with Image Preview</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
.upload-container {
margin-bottom: 20px;
}
#preview {
display: none;
max-width: 300px;
max-height: 300px;
margin-top: 20px;
border: 1px solid #ddd;
padding: 5px;
}
</style>
</head>
<body>
<div class="upload-container">
<label for="file-upload">Upload an Image:</label>
<input type="file" id="file-upload" accept="image/*" />
</div>
<div id="image-preview">
<img id="preview" alt="Image Preview" />
</div>
<script>
// JavaScript to handle image upload and display
document
.getElementById("file-upload")
.addEventListener("change", function (event) {
const file = event.target.files[0];
if (file) {
const reader = new FileReader();
// Set image preview source once file is loaded
reader.onload = function (e) {
const preview = document.getElementById("preview");
preview.src = e.target.result;
preview.style.display = "block"; // Show the image
};
reader.readAsDataURL(file);
}
});
</script>
</body>
</html>
Application.java
Java
import java.time.Duration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import com.google.errorprone.annotations.Var;
public class Application {
public static void main(String[] args) throws InterruptedException {
// Set the path to the ChromeDriver executable
System.setProperty("webdriver.chrome.driver", "chromedriverpath");
// Initialize WebDriver
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://127.0.0.1:5500/htmlfile.html");
driver.manage().window().maximize();
// Locate the file input element
WebElement uploadElement = driver.findElement(By.id("file-upload"));
Thread.sleep(2000); // Using sleep for simplicity;
// Use sendKeys to provide the file path
uploadElement.sendKeys("C:\\Users\\3517tu\\Downloads\\gfgFooterLogo.png");
WebElement imagePreview = driver.findElement(By.id("preview"));
// Wait for the image to load
Thread.sleep(2000); // Using sleep for simplicity;
// Check if the image is visible
if (imagePreview.isDisplayed() && imagePreview.getAttribute("src") != null && !imagePreview.getAttribute("src").isEmpty()) {
System.out.println("Image is successfully uploaded and visible in the preview.");
} else {
System.out.println("Image is not visible in the preview.");
}
// Close the browser
driver.quit();
}
}
Output:
outputConclusion
In conclusion, automating file uploads with Selenium WebDriver simplifies the process of testing web applications that involve file handling. By the sendKeys()
method to upload files, you can ensure that your test scripts remain robust and easy to manage. File upload automation plays a significant role in enhancing the efficiency of testing workflows, especially for applications that frequently require file inputs.
Similar Reads
File Upload using Selenium WebDriver and Java Robot Class File uploads are a common task in web automation, and handling them effectively can be crucial for testing file-related functionalities. While Selenium WebDriver provides a straightforward way to interact with file upload elements, sometimes the built-in methods fall short. In such cases, combining
3 min read
How to Use AutoIT with Selenium Webdriver? Selenium WebDriver has revolutionized web automation, but it faces limitations when dealing with native Windows dialogs. This is where AutoIT comes to the rescue, bridging the gap between web and desktop automation. For testers and developers working on web applications, understanding how to integra
8 min read
How to Install Selenium WebDriver on Windows for Java? Selenium is an open-source tool for automating testing of web applications which is free and it supports various programming languages such as C#, Java, Perl, PHP, Python, and Ruby. Selenium Webdriver is most well known or you can say famed with Java as of now. In this article, we will look into how
3 min read
How to Automate Click Using Selenium WebDriver? Selenium is one of the most popular and powerful tools for automating web applications. Selenium is widely used for automating user interactions like filling out forms, clicking on a button, navigating to a web page, and many more. One of the most common tasks while working with Selenium is clicking
5 min read
How to do session handling in Selenium Webdriver using Java? In Selenium WebDriver, managing browser sessions is crucial for ensuring that each test runs independently and without interference. A browser session in Selenium is identified by a unique session ID, which helps track and manage the session throughout the test. Proper session handling in Selenium W
4 min read