Open In App

File Upload using Selenium WebDriver and Java Robot Class

Last Updated : 11 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 Selenium WebDriver with Java’s Robot class can offer a robust solution.

This article will guide you through the process of uploading files using Selenium WebDriver and the Java Robot class, ensuring a seamless automation experience.

Example of File Upload using Selenium WebDriver and Java Robot Class

Here is a detailed explanation of each step with the accompanying code example:

Java
package com.example.tests;

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;
import io.github.bonigarcia.wdm.WebDriverManager;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;

public class FileUploadExample {
    public static void main(String[] args) {
        // Setup WebDriverManager for ChromeDriver
        WebDriverManager.chromedriver().setup();
        
        // Create a new instance of the Chrome driver
        WebDriver driver = new ChromeDriver();

        try {
            // Maximize the browser window
            driver.manage().window().maximize();

            // Navigate to the specified URL
            driver.get("https://demoqa.com/upload-download");

            // Find the "Choose File" button element on the webpage
            WebElement button = driver.findElement(By.xpath("//input[@id='uploadFile']"));

            // Use Actions class to move to the "Choose File" button and click on it
            Actions act = new Actions(driver);
            act.moveToElement(button).click().perform();

            // Initialize the Robot class (used for simulating keyboard and mouse actions)
            Robot rb = new Robot();
            rb.delay(2000);  // Wait for 2 seconds to ensure the file dialog is open

            // Copy the file path to the clipboard
            StringSelection ss = new StringSelection("Downloads\\nestedframes.html");//path which you want to upload the file 
            Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);

            // Simulate pressing CTRL + V to paste the copied file path
            rb.keyPress(KeyEvent.VK_CONTROL);
            rb.keyPress(KeyEvent.VK_V);
            rb.keyRelease(KeyEvent.VK_CONTROL);
            rb.keyRelease(KeyEvent.VK_V);

            // Simulate pressing ENTER to confirm the file selections
            rb.keyPress(KeyEvent.VK_ENTER);
            rb.keyRelease(KeyEvent.VK_ENTER);

            // Print a message to the console indicating that the file has been uploaded
            System.out.println("File Uploaded");
        } catch (Exception e) {
            // Print any exception that occurs during execution
            e.printStackTrace();
        } finally {
            // Close the browser after the script completes
            driver.quit();
        }
    }
}


Explanation

  1. WebDriver Setup: WebDriverManager simplifies the driver management process.
  2. Browser Interaction: The ChromeDriver instance is created and maximized.
  3. File Dialog Interaction: The Robot class is used to handle the file dialog that Selenium cannot interact with directly.

Output

output-of-robot-class-file-upload
robol class file upload

Conclusion

Uploading a file using Selenium WebDriver combined with the Java Robot class is an effective method for handling file uploads in web applications, especially when the standard sendKeys method isn't sufficient. This process involves automating the interaction with the file upload dialog, which can be particularly useful when dealing with non-standard input elements or browser-specific behaviors.

By following the steps and using the provided code example, you can integrate file upload functionality into your automated testing scripts with ease. This approach ensures that your tests cover the entire user interaction flow, including file uploads, contributing to a more robust and reliable application.


Next Article
Article Tags :

Similar Reads