How to Handle File Upload in Selenium
Faisal Khatri
Posted On: August 29, 2024
286809 Views
10 Min Read
When performing website testing, validating file upload functionality is crucial as users need to upload documents and images, such as in job portals, eCommerce websites, cloud storage systems, and others.
Automating this process ensures reliability and efficiency in testing these functionalities, and automated testing tools like Selenium provide effective solutions for this task. In this blog, we delve into how to handle file upload in Selenium, exploring techniques to handle file upload and automate file upload functionality.
TABLE OF CONTENTS
Why Selenium for Handling File Upload?
Selenium is an open-source collection of tools and libraries to automate interactions with web browsers. Being open-source and free, it has become a popular choice for automation testing in the global testing community. With the release of Selenium 4, Selenium has become W3C compliant. Selenium Manager has also been introduced, simplifying driver and browser management.
When handling file uploads, Selenium offers extensive browser support, robust automation capabilities, and flexibility for efficiently handling different file types and dynamic interactions. Instead of interacting with the file upload dialog, it provides a way to upload files without opening the dialog box.
Methods to Handle File Upload in Selenium
To upload files locally, we can use the Selenium sendKeys() method and give the file path in the method parameter. However, the same thing will not work remotely as do locally. To upload files remotely, we need to use the setFileDetector() method of the RemoteWebDriver class.
Using the setFileDetector() method, the RemoteWebDriver acknowledges that we are uploading files for Selenium testing over either a local or remote machine.
With this feature of Selenium WebDriver, we do not have to write separate code for uploading files over locally or remotely hosted web applications.
We have the following methods for file upload in Selenium WebDriver:
- sendKeys() method
- Robot class
- AutoIt
Automate file upload testing across 3000+ real browsers. Try LambdaTest Now!
Automate file upload testing across 3000+ real browsers.
It is always preferred to use the built-in features Selenium provides to upload files. The Selenium sendKeys() method is one such method in Selenium. It directly applies to input tags that have an attribute as type=’file’.
Here is an example of file upload in Selenium and Java using the sendKeys() method:
1 2 |
WebElement addFile = driver.findElement(By.cssSelector("input[type='file']")); addFile.sendKeys("/Users/Desktop/sample_file.jpeg"); |
File Upload in Selenium Using Robot Class
Using the Robot class is another good option for uploading a file in Selenium. Robot class is an AWT class package in Java. This class helps automate windows based alerts, popups, or native screens. It is independent of the operating system.
Let’s take an example of the PDF to WORD Converter website and upload a PDF file using Robot class with Selenium.
The following test script will allow us to file upload in Selenium using the Robot class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
@Test public void testFileUpload() throws AWTException { WebDriver driver = new ChromeDriver(); driver.get("https://www.ilovepdf.com/pdf_to_word"); driver.findElement(By.id("pickfiles")) .click(); selectFile("C:\\Users\\Faisal\\Downloads\\Smallpdf.pdf"); WebElement convertToWordBtn = driver.findElement(By.id("processTask")); assertTrue(convertToWordBtn.isDisplayed()); driver.quit(); } |
This code will navigate to the PDF to WORD converter website, locate the Select PDF file button, and perform a click on it. Next, the selectFile() method that accepts the file path as a String is called, and it will perform file selection actions using the Robot class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public void selectFile(String path) throws AWTException { StringSelection strSelection = new StringSelection(path); Clipboard clipboard = Toolkit.getDefaultToolkit() .getSystemClipboard(); clipboard.setContents(strSelection, null); Robot robot = new Robot(); robot.delay(2000); 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.delay(4000); robot.keyRelease(KeyEvent.VK_ENTER); } |
Using Robot class, ideally, the path is pasted in the filename field of the file upload window, and the Enter key is pressed, which helps select the file for upload.
File Upload in Selenium Using AutoIt
AutoIt is an open-source test automation tool that automates native windows-related popups. However, AutoIt is not recommended for file upload. It can be used as an option if nothing works.
We will upload a sample file using the PDF to the WORD converter website.
Here are the following steps to integrate AutoIt with Selenium tests to upload a file.
- Install AutoIt.
- Navigate to C:\Programs Files\AutoIt3\SciTE\ and run the SciTE.exe file. Add the following script to the editor:
- Save the file with a meaningful name like uploadfile.au3.
- Compile the uploadfile.au3 file by right-clicking on it and selecting the Compile Script(x64) option to convert the file to uploadfile.exe.
- Save the file with the .exe extension and run using the following command:
1 2 3 |
ControlFocus("Open","","Edit1") ControlSetText("Open","","Edit1",""C:\Users\Faisal\Downloads\Smallpdf.pdf"") ControlClick("Open","","Button1") |
1 |
Runtime.getRuntime().exec(). |
The following test script will allow file upload in Selenium using AutoIt.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
@Test public void testFileUploadDownload() throws IOException, InterruptedException { driver.get("https://www.ilovepdf.com/pdf_to_word"); driver.findElement(By.id("pickfiles")) .click(); Thread.sleep(5000); Runtime.getRuntime() .exec("C:\\Users\\Faisal\\AutoIt_script\\uploadfile.exe"); Thread.sleep(5000); WebElement convertToWordBtn = driver.findElement(By.id("processTask")); assertTrue(convertToWordBtn.isDisplayed()); } |
The test will navigate the PDF to WORD converter website and locate the Select PDF file button. Using the script Runtime.getRuntime().exec() method, the AutoIt upload script will be executed, and the upload action will be performed to select the PDF file for upload.
Finally, an assertion will be performed to check that the Convert to WORD button is displayed, ensuring the file was uploaded successfully.
In order to further enhance your Selenium automation testing, you can consider exploring AI testing agents like KaneAI.
KaneAI is a smart AI test assistant for high-speed quality engineering teams. With its unique AI-driven features for test authoring, management, and debugging, KaneAI allows teams to create and evolve complex test cases using natural language.
Demo: Handling File Upload in Selenium
Now, let us demonstrate and check how to upload files using Selenium on both the local and cloud grid. As a part of this blog, we will focus on leveraging the sendKeys() method to upload files and use the below test scenario for local and cloud grid execution.
Test Scenario:
|
File Upload in Selenium on Local Grid
Let’s look at how to handle file upload in Selenium on the local grid.
Test Implementation:
Below is the test script, which demonstrates how to upload files in Selenium WebDriver using Chrome browser on a local machine:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
public class UploadDemoTest { private WebDriver driver; @BeforeTest public void setup() { driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(20)); } @Test public void testFileUpload() { driver.get("https://www.lambdatest.com/selenium-playground/upload-file-demo"); WebElement chooseFile = driver.findElement(By.id("file")); chooseFile.sendKeys("/Users/faisalkhatri/Blogs/file_upload_download/file_example_JPG_100kB.jpg"); String successMessage = driver.findElement(By.id("error")).getText(); assertEquals(successMessage, "File Successfully Uploaded"); } @AfterTest public void tearDown() { driver.quit(); } } |
Code Walkthrough:
There are three methods defined in the UploadDemoTest class that is created inside a new package uploaddownloaddemo. The setup() method that will run before any of the tests get executed takes care of starting a new Chrome browser session and applying an implicit wait of 20 seconds.
The testFileUpload() method will perform all the file upload steps. It will first navigate to the Upload File Demo page, locate the Choose file button, and upload the file using the sendKeys() method.
The assertion will be performed on the text displayed after successfully uploading the file. This success message text will be located using the ID locator in Selenium, and the assertEquals() method of TestNG is called to check that the correct success message is displayed after the file upload is complete.
The tearDown() method is called the quit() method, and it will gracefully close the browser session.
Test Execution:
The following screenshot from IntelliJ IDE shows the successful execution of the test on the local machine:
When we refer to practical and real-time scenarios, the requirement to perform automated browser testing might involve hundreds of browsers + OS combinations to be tested. Remember, the desired capabilities are bound to go bigger as your web application scales over time.
In such scenarios, maintaining an in-house Selenium infrastructure is time-consuming and expensive. You will need to hire more machines and resources on-board. Fortunately, an online Selenium Grid offered by cloud testing platforms such as LambdaTest helps us execute automated tests using Selenium and test file upload functionality across different browsers and OS combinations.
File Upload in Selenium on Cloud Grid
Let’s look at how to handle file upload in Selenium on the cloud grid offered by LambdaTest.
LambdaTest is an AI-driven test execution platform where you can test websites on 3000+ real browsers and operating systems. That way, you won’t have to worry about maintaining your Selenium Grid, as LambdaTest will provide you with an online Selenium Grid with zero downtime.
Test Implementation:
Let’s run the same scenario on the LambdaTest. We will have to make some changes to the setup() method and the test script.
We will create a new test class in the same uploaddownloaddemo package and name it UploadDemoLambdaTest.
Below is the test script used for demonstrating the file upload test scenario on the latest version of Chrome browser on the Windows 11 platform:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
public class UploadDemoLambdaTest { private RemoteWebDriver driver; private String status = "failed"; @BeforeTest public void setup() { final String userName = System.getenv("LT_USERNAME") == null ? "LT_USERNAME" : System.getenv("LT_USERNAME"); final String accessKey = System.getenv("LT_ACCESS_KEY") == null ? "LT_ACCESS_KEY" : System.getenv("LT_ACCESS_KEY"); final String gridUrl = "@hub.lambdatest.com/wd/hub"; try { this.driver = new RemoteWebDriver(new URL("http://" + userName + ":" + accessKey + gridUrl), getChromeOptions()); } catch (final MalformedURLException e) { System.out.println("Could not start the remote session on LambdaTest cloud grid"); } driver.setFileDetector(new LocalFileDetector()); this.driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(20)); } @Test public void testFileUpload() { driver.get("https://www.lambdatest.com/selenium-playground/upload-file-demo"); WebElement chooseFile = driver.findElement(By.id("file")); chooseFile.sendKeys("/Users/faisalkhatri/Blogs/file_upload_download/file_example_JPG_100kB.jpg"); String successMessage = driver.findElement(By.id("error")).getText(); assertEquals(successMessage, "File Successfully Uploaded"); status = "passed"; } public ChromeOptions getChromeOptions() { final var browserOptions = new ChromeOptions(); browserOptions.setPlatformName("Windows 11"); browserOptions.setBrowserVersion("latest"); final HashMap<String, Object> ltOptions = new HashMap<String, Object>(); ltOptions.put("project", "LambdaTest Grid Demo"); ltOptions.put("build", "Upload File page demo"); ltOptions.put("name", "Upload File test on LambdaTest cloud grid"); ltOptions.put("w3c", true); ltOptions.put("plugin", "java-testNG"); browserOptions.setCapability("LT:Options", ltOptions); return browserOptions; } @AfterTest public void tearDown() { this.driver.executeScript("lambda-status=" + this.status); this.driver.quit(); } } |
Code Walkthrough:
The testFileUpload() method is the same as in the earlier section, where we ran the tests on a local machine. The change is in the configuration part, as we need to configure the platform, browser, and browser versions to run the tests on the LambdaTest cloud grid.
Other capabilities such as project name, build, and test name can also be supplied as browser options and finally used in the parameters while instantiating the RemoteWebDriver.
We will use the Selenium RemoteWebDriver here to run the tests on the cloud grid. We would need the LambdaTest Username, Access Key, and grid URL to set the configuration to execute tests on the cloud grid.
Additionally, the setFileDetector() method of the RemoteWebDriver class needs to be called, as it will help upload files to the cloud grid.
In the tearDown() method, there is an additional statement where the executeScript() method of the RemoteWebDriver class. It sets the test status, i.e., pass or fail, as per the test execution.
Test Execution:
Run your test for file upload in Selenium. After that, to view your test results, go to the LambdaTest Web Automation Dashboard.
You can also watch this video to learn how to upload and download files in Selenium WebDriver using different techniques.
Subscribe to the LambdaTest YouTube Channel and stay updated with the latest tutorials.
Wrapping Up
For a website that allows users to upload files, we need to ensure they work seamlessly across all browsers and platforms.
Selenium testing can easily automate the download & upload file functionality of the web application. Although Selenium can help you execute test cases in local infrastructure, it is always recommended to go for a cloud-based Selenium Grid to save time and resources.
Frequently Asked Questions (FAQs)
How do you upload a file in Selenium?
To upload a file in Selenium, use the sendKeys() method on the file input element, specifying the file path as the argument.
How to upload a file without input in Selenium?
You can upload a file without an input element in Selenium by using JavaScript to simulate the file selection process or by directly interacting with the browser’s file dialog.
How to validate file upload in Selenium?
Validate file upload in Selenium by checking the presence of the uploaded file’s name or verifying any success message or element that appears after a successful upload.
Got Questions? Drop them on LambdaTest Community. Visit now