Uploading & Downloading a File using Selenium Webdriver: Welcome you with another new post on the Softwaretestingo blog. This post will discuss one of the common features we frequently use during file upload and download automation. We will understand how we can handle such scenarios in Java Selenium and the different ways of file uploading features.
If you are going to automate a web application, you must come to a scenario where you must upload files to process the data. So when you click on the browse button that time, it will prompt a dialogue box. We can handle such a situation in different ways:
- Sendkeys()
- Robot Class
- AutoIT
- Sikuli
Let us review it individually and understand how their users upload files in a web application.
Using Sendkeys()
This is one of the basic methods most testers follow to perform the file-uploading operation. Still, now we are using the sendkeys() method to send some data to an active element in our framework. Similarly, this method can send the absolute path details to the browser file dialogue. To make this approach work, you have to follow the guidelines below:
The file textbox properties must be “Enabled” & “Visible.”
The file’s path must be the absolute path
Not to perform a “Click” action to launch the file dialogue
<html> <body> <div tabindex="500" class="btn btn-primary btn-file"><i class="glyphicon glyphicon-folder-open"></i> <span class="hidden-xs">Browse …</span><input id="input-4" name="input4[]" type="file" multiple="" class=""></div> </div><div id="kvFileinputModal" class="file-zoom-dialog modal fade" tabindex="-1" aria-labelledby="kvFileinputModalLabel"><div class="modal-dialog modal-lg" role="document"> </body> </html>
Test Scenario:
When you click on choose files, a dialogue box will open, and in that file name text box, we have to enter the absolute file path in the file name text box; after that, click on the open button. Once the file is uploaded successfully, it is displayed beside the choose file button.
Now, we are trying to do the same operation using the same webdriver. For this, we will use the sendkeys() method, by which we will send the file path details to the file path name text box.
Here is the below code for the above scenario:
package com.softwaretestingo.fileupload; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class UsingSendKeys { public static void main(String[] args) throws InterruptedException { WebDriver driver=new ChromeDriver(); driver.manage().window().maximize(); driver.get("https://demo.softwaretestingo.com/upload-download/"); Thread.sleep(3000); driver.findElement(By.id("uploadFile")).sendKeys("D:\\Workspace\\Automation\\SeleniumPractice\\Resources\\SoftwareTestingO.png"); Thread.sleep(3000); driver.close(); } }
Using robot Class
As we know, we can upload the file with the help of a keyboard and mouse. So, we can use the Robot class as an alternative for file uploading. In this case, we can use the Robot class to take control of the mouse and keyboard. After getting the control, we can do the sequence of operation of mouse and keyboard usage.
Steps:
- Copy the absolute path into the system clipboard
- Click on the choose file button and use CTRL+V and CTRL+Enter
Note:
- During the use of the robot class, each key should be pressed and released respectively.
- Robot class is not a part of Selenium but comes with Java.
package com.softwaretestingo.fileupload; import java.awt.AWTException; import java.awt.Robot; import java.awt.Toolkit; import java.awt.datatransfer.StringSelection; import java.awt.event.KeyEvent; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class UsingRobotClass { public static void main(String[] args) throws InterruptedException, AWTException { WebDriver driver=new ChromeDriver(); driver.manage().window().maximize(); driver.get("https://blueimp.github.io/jQuery-File-Upload/"); Thread.sleep(3000); driver.findElement(By.cssSelector(".btn.btn-success.fileinput-button")).click(); driver.switchTo().activeElement(); StringSelection ss=new StringSelection("D:\\Workspace\\Automation\\SeleniumPractice\\Resources\\SoftwareTestingO.png"); Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null); Thread.sleep(3000); Robot r=new Robot(); r.keyPress(KeyEvent.VK_CONTROL); r.keyPress(KeyEvent.VK_V); r.keyRelease(KeyEvent.VK_V); r.keyRelease(KeyEvent.VK_CONTROL); r.keyPress(KeyEvent.VK_ENTER); r.keyRelease(KeyEvent.VK_ENTER); Thread.sleep(3000); driver.quit(); } }
Methods Used in Robot Class
- robot.keyPress(KeyEvent.VK_CONTROL); this method is used to press the ‘control’ key in the keyboard
- robot.keyPress(KeyEvent.VK_V); this method is used to press the ‘V’ key in the keyboard (it will automatically Press (ctrl+v) on the keyboard)
- robot.keyPress(KeyEvent.VK_CONTROL); this method is used to release the ‘control’ key in the keyboard
- robot.keyPress(KeyEvent.VK_V); this method is used to press the ‘V’ key in the keyboard (it will Release (ctrl+v) on the keyboard & paste the file in the desired location)
- robot.keyPress(KeyEvent.VK_ENTER) && robot.keyRelease(KeyEvent.VK_ENTER); Press and Release the ‘Enter’ button (in the popup window, if you press ‘Enter,’ it will trigger the ‘Open’ button in the window)
Note: With the help of the ROBOT class, we can easily upload/download files. But in the case of bulk upload, we need to recurrently perform ‘KeyPress’ or ‘Key Release’ methods, which is a limitation of this approach.
Using AutoIT
AutoIt Tool is an open-source tool. It is a freeware BASIC-like scripting language designed for automating the Windows GUI and general scripting. It uses a combination of simulated keystrokes, mouse movement, and window/control manipulation to automate tasks in a way that is not possible or reliable with other languages (e.g., VBScript and SendKeys). AutoIt is also very small and self-contained and will run on all versions of Windows out of the box with no annoying “runtimes” required!
The question is how we upload files using the AutoIT Tool in Selenium WebDriver.
Follow the below steps:
- We need to download the latest version from the AutoIT Official website. you can get the link from here
- After successful installation, you can see the different options in the Windows startup menu.
- In Windows startup, you can choose “AutoIt Window Info.” Click on that. After clicking “AutoIt Window Info,” a new popup window will open.
- Again, go to the AutoIT official website to download the AutoIT Editor. you can download the editor from this link
- Download and Install the editor. After successfully installing the editor, you can find an option SciTE, in the Windows startup menu.
- Click on SciTE to open the editor to write the script to upload a file.
How to Generate AutoIT Automation Script:
Until we know how to install AutoIT, we will learn to write the automation script to automate the file-uploading process.
- Open the File upload URL, click choose file, then keep the dialogue.
- From the AutoIT Window Info window, drag the Finder Tool to the required component to get the detailed properties of that component, such as component ID, text, and title.
For this example, the details are:
title:
Component id:
- Before writing the automation script, refer to the AutoIT built-in functions [link] page to better understand the functions used.
Based on those details, you can prepare the automation, and that looks something like below:
Focus on the Edit1 component.
ControlFocus(“Choose File to Upload”, “”, “Edit1”);
Click Edit1 component.
ControlClick(“Choose File to Upload”, “”, “Edit1”);
Input upload file path in Edit1 input text box.
ControlSetText(“Choose File to Upload”,””, “Edit1”, “C:\WorkSpace\JEETT.pdf”);
Click the Open button to choose the upload file.
ControlClick(“Choose File to Upload”, “”, “Button1”);
- Save the file after saving the file, and you will get a new file with an extension filename.au3
- If you run the script by right-clicking on the file and selecting the run script, you can find that the file is uploaded.
- We must compile the saved filename for use in our Selenium automation script.au3 file, you can do that by right-clicking on the file and choosing compile script.
How to Use The AutoIT Automation Script in Selenium
Until this, we have seen how to install and preparation the AutoIT automation script. Now, we try to learn how to use the AutoIT automation script in a real-world example.
We can use the below syntax to execute any .exe file
Runtime.getRuntime(). exec(“C:\\WorkSpace\\uploadFile.exe”);
public class TestUploadFileWithAutoIT { public static void main(String[] args) { TestUploadFileWithAutoIT example = new TestUploadFileWithAutoIT(); example.uploadFileUseAutoITChrome(); } /* Upload in Chrome. */ public void uploadFileUseAutoITChrome() { ChromeDriver driver = null; try { // Specify Chrome Driver executable path. String chromeDriverPath = "C:\\Workspace\\dev2qa.com\\Lib\\chromedriver_win32\\chromedriver.exe"; //Assign chrome driver path to system property "webdriver.chrome.driver" System.setProperty("webdriver.chrome.driver", chromeDriverPath); //Initiate Chrome driver instance. driver = new ChromeDriver(); /* Upload page*/ String uploadFileDisplayUrl = "http://www.dev2qa.com/demo/upload/uploadFileTest.html"; // Display upload page. driver.get(uploadFileDisplayUrl); //Get the upload web element by it's name "uploadFileInputBox" WebElement element = driver.findElement(By.name("uploadFileInputBox")); //Click the upload button to open select file window. element.click(); Thread.sleep(1000); Runtime.getRuntime().exec("C:\\WorkSpace\\uploadFile.exe"); Thread.sleep(5000); // Click the upload form submit button. driver.findElement(By.name("uploadFileSubmitBtn")).click(); Thread.sleep(3000); } catch(Exception ex) { ex.printStackTrace(); } finally { if(driver!=null) { driver.close(); driver = null; } } } }
Using Sikuli
Sikuli is an open-source Graphical User Interface automation tool. Sikuli will be used to automate anything that you can view on the screen. It uses image recognition to speak with the GUI elements. When there is no easy access to a GUI’s source code, this is one of the best ways to get the appropriate response.
package uploads; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.sikuli.script.FindFailed; import org.sikuli.script.Pattern; import org.sikuli.script.Screen; public class FileUpload_Sikuli { public static void main(String[] args) throws Exception { // TODO Auto-generated method stub System.setProperty("webdriver.chrome.driver", "path of chromedriver.exe"); WebDriver wd=new ChromeDriver(); wd.get("path of url"); wd.findElement(By.id("fileupload")).click(); Screen sikuliscreen=new Screen(); String file1="\"C:\\Users\\rkandula\\Desktop\\window_Textbox.png\""; String file2="\"C:\\Users\\rkandula\\Desktop\\window_openbtn.png\""; String mutliplefiles=file1+file2; System.out.println(total); Pattern window_popup_textbox=new Pattern("C:\\Users\\rkandula\\Desktop\\window_Textbox.png"); Pattern window_openbtn=new Pattern("C:\\Users\\rkandula\\Desktop\\window_openbtn.png"); sikuliscreen.wait(window_popup_textbox, 20); sikuliscreen.type(window_popup_textbox, mutliplefiles); sikuliscreen.click(window_openbtn); Thread.sleep(3000); wd.close(); } }
If the screen resolution changes, Sikuli’s behavior will differ. So, running the scripts on the same resolution as the images captured is advisable. In case the pixel size of an image changes, it throws a FindFailed exception. These distinct file upload methods are tried & tested by us. They have the potential to be integrated easily with your code. Here, we have supported content with relevant images and coding to help you get a different perspective on uploading files in your Selenium projects efficiently.