Modern web applications have evolved to offer highly interactive and user-centric experiences, and file upload is one of them. Be it uploading a picture, importing data through CSV, or submitting a document, users experience smooth, fast, and secure uploads. Validating the uploading of a file in automation testing can be tricky. File uploads generally involve interactions with the operating system, unlike other web elements. Selenium WebDriver doesn’t offer native support to interact with an operating system, but with the right strategies, you can reliably automate file uploads using Selenium. In this article, we will talk about the different methods of uploading files in Selenium using practical examples and look at the best practices for formulating robust and efficient tests.
Importance of Testing File Uploads
Before understanding the implementation of testing file uploads in Selenium, let us see why it is important to test the functionality.
- File Validation – Ensuring that the file type and file size are as expected.
- Security – Preventing the upload of malicious files.
- Performance – Monitoring the time it takes to upload files, especially large files.
- Cross-browser Compatibility – Ensuring the upload functionality works as expected across all supported browsers.
- UI/UX Testing – Verifying the user flow and the success or error messages.
Basics of File Upload in Selenium
Before we begin, you need to understand that Selenium alone does not allow direct interaction with OS (Windows or Mac) level windows. Selenium can only interact with the web elements present within the DOM. This means that when you see a file upload button like “Choose File”, and the HTML tag is <input type = “file”>, Selenium can interact with it.
You can use one of the following ways to automate file upload using Selenium-
- Use sendKeys() function.
- Use the Robot class
- Integrate with AutoIT (Windows-only automation tool for handling native dialogs)
Using sendKeys() for File Upload in Selenium
The sendKeys() method sends the absolute file path directly to the file input element of type=”file”. This eliminates the need to interact with the native OS file picker dialog, making it the most compatible and cross-platform way to upload a file using Selenium.
We will be using the demoqa practice website for our demonstration. Let us look at the working code for the same.
package fileUploads;
import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
public class UploadFileUsingSendKeys {
@Test
public void uploadFile() {
//Launch browser
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
// Navigate to file upload form
driver.get("https://demoqa.com/upload-download");
// Locate file input field and upload file using sendKeys()
driver.findElement(By.id("uploadFile")).sendKeys("/Users/macair/Documents/downloadImg.png");
// Optional: Click Upload button- not required in our demo website
//driver.findElement(By.id("id of the upload button")).click();
// Add assertions or validations here
// Close browser
driver.quit();
}
}
Upon running the code, you will notice that the file gets uploaded and the test passes.
What if there is no <input type = “file”>?
In many modern web apps, JavaScript is used to implement custom file uploads, which hides the actual file input behind a styled <div> or triggers a native file dialog using a custom button. In such scenarios,
- Inspect if there is an invisible <input type = “file”> in the DOM.
- Use JavaScriptExecutor to trigger click events on hidden file input elements.
- If none of the above work, use tools like Robot Class or AutoIT.
Using Robot Class To Upload a File In Selenium
In the code below, we are using the Robot class to upload a file to an image converter website.
package fileUploads;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;
import java.time.Duration;
import java.net.MalformedURLException;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class UploadFileUsingRobotClass {
public void uploadFileWithRobot() throws AWTException, InterruptedException, MalformedURLException {
// Launch browser
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
// Navigate to the file upload form
driver.get("https://www.ilovepdf.com/jpg_to_pdf");
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
// Click the 'Choose File' button to open the file dialog
WebElement uploadButton = driver.findElement(By.xpath("//*[@id=\"pickfiles\"]/span"));
uploadButton.click();
// Wait a second for the dialog to open
Thread.sleep(1000);
// Prepare the file path to be copied
String filePath = "/Users/macair/Documents/downloadImg.png";
StringSelection filePathSelection = new StringSelection(filePath);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(filePathSelection, null);
// Create Robot instance
Robot robot = new Robot();
// Simulate ⌘ + Tab to focus on the dialog (Mac-specific)
robot.keyPress(KeyEvent.VK_META);
robot.keyPress(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_META);
Thread.sleep(500);
// Simulate ⌘ + Shift + G to open 'Go to folder'
robot.keyPress(KeyEvent.VK_META);
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_G);
robot.keyRelease(KeyEvent.VK_G);
robot.keyRelease(KeyEvent.VK_SHIFT);
robot.keyRelease(KeyEvent.VK_META);
Thread.sleep(500);
// Paste the file path using ⌘ + V
robot.keyPress(KeyEvent.VK_META);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_META);
Thread.sleep(500);
// Press Enter to confirm folder
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
Thread.sleep(500);
// Press Enter to upload the file
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
Thread.sleep(1000);
// Optional: Add validation/assertion if needed
// Close browser
driver.quit();
}
public static void main(String[] args) throws AWTException, InterruptedException, MalformedURLException {
new UploadFileUsingRobotClass().uploadFileWithRobot();
}
}
When you execute the code, you will notice that the file that you wanted to upload is uploaded from your local system and displayed on the web application as shown in the screenshot below.
And there you go, you have successfully uploaded a file from your system using Selenium. Let us now see how we can use a tool like AutoIT to achieve the same.
Using AutoIT To Upload a File In Selenium
Third-party tools like AutoIT can be integrated with Selenium to upload files in Windows systems. To do so, you need to download AutoIT on your system and write a basic script to simulate the file upload. The script then needs to be compiled as an .exe file to be used in the Selenium code.
- In the AutoIT Text Editor, create a new file and copy the code below.
; AutoIT script to handle file upload dialog
WinWaitActive("Open") ; waits for the file upload window to appear
Send("local path where your file resides in your system") ; update with your file path
Send("{ENTER}")
2. Save the files as fileUploadScript.au3.
3. Compile the file into an exe.
Now, we are all set to use the AutoIT script in our Selenium code to upload a file from the Windows system. Below is the Selenium code for the same.
package testGrid.fileUpload;
import java.io.IOException;
import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class FileUploadWithAutoIt {
public static void main(String[] args) throws IOException, InterruptedException {
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
// Navigate to the file upload form
driver.get("https://www.ilovepdf.com/jpg_to_pdf");
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
// Click the 'Choose File' button to open the file dialog
WebElement uploadButton = driver.findElement(By.xpath("//*[@id=\"pickfiles\"]/span"));
uploadButton.click();
// Wait a second for the dialog to open
Thread.sleep(1000);
// Run AutoIT script to handle the upload dialog
Runtime.getRuntime().exec("path location of fileUploadScript.exe in your system");
// Optional: Wait for upload to complete or validate
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
driver.quit();
}
}
Upon executing the code, you will notice that the file gets uploaded with the Windows-based interaction being handled by the AutoIT script.
Best Practices For Uploading Files in Selenium
- Use absolute paths in your test scripts to avoid path resolution issues.
- Avoid OS-dependent solutions like AutoIT or Robot class, unless necessary.
- Use assertions to validate that the uploaded file has been processed by the application.
- Clean up test files after uploading to avoid clutter and flaky tests.
- Use a loop and dynamic locators when uploading multiple files, especially for apps that support multiple file inputs.
Conclusion
File uploading appears to be an easy process, but it has many complexities. While automating file uploads with Selenium, it is important to understand how the DOM, file inputs, and browser native components behave. Be it a traditional <input type=”file”> element or a custom JavaScript-based UI, Selenium offers robust options like sendKeys(), integration with Robot Class and AutoIT to handle these scenarios effectively. By using the right strategy, you can excel at testing the applications seamlessly for complex scenarios.