Uploading & Downloading a File using Selenium Webdriver: Welcome you with another new post on Softwaretestingo blog. In this post, we are going to discuss one of the common features which we are frequently using during the automation that files upload and download. We are going to understand how we can handle such scenarios in Java selenium and the different ways of file uploading feature.
If you are going to automate a web application, then you must come to a scenario where you need to uploading 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 try to go through with one by one and understand their users to upload files in a web application.
Using Sendkeys()
This is one of the basic methods which is followed by most of the testers 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, we can use this method to send the absolute path details to the browser file dialogue. To make this approach works, you have to follow the below guidelines:
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 upload successfully, the file is displayed beside the choose file button.
Check Also: Selenium WebDriver Tutorials
Now we are trying to do the same operation using the same webdriver. For this, we are going to use the sendkeys() method by which we are going to send the file path details to the file path name text box.
Here is the below code for the above scenario:
import java.io.IOException; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class FileUpload { public static void main(String[] args) throws IOException { // Setting chrome driver path System.setProperty(“webdriver.chrome.driver”,”./exefiles/chromedriver.exe”); // Launching and maximizing browser WebDriver driver= new ChromeDriver(); driver.manage().window().maximize(); // Launching URL driver.get(“file:///C://Users//Stestingo//Desktop//FileUpload.html”); // Locating input tag which as type as file. WebElement searchBox= driver.findElement(By.id(“files”)); // Sending file name as the argument to the input tag searchBox.sendKeys(“F:\\Eclipse_WS\\SoftwareTestingo\\ScreenCapturesPNG\\TypeUsingJS.jpg”); } }
Using robot Class
As we know that we can uploading the file with the help of 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 robot class, each key should be pressed and released respectively.
- Robot class is not a part of Selenium, and its comes with Java.
package testpack1; import java.awt.Robot; import java.awt.Toolkit; import java.awt.datatransfer.StringSelection; import java.awt.event.KeyEvent; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class FileUpload_Robot { static WebDriver driver; public static void main(String[] args) throws Exception { System.setProperty("webdriver.chrome.driver", "D:\\Automation\\Softwares\\chromebrowser\\chromedriver_win32 (2)\\chromedriver.exe"); WebDriver driver=new ChromeDriver(); driver.get("http://toolsqa.com/automation-practice-form/"); driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS); driver.manage().deleteAllCookies(); driver.findElement(By.id("photo")).click(); Thread.sleep(2000); uploadFile("C:\\Users\\rkandula\\Desktop\\ImpData.txt"; Thread.sleep(2000); } public static void setClipboardData(String string) { //StringSelection is a class that can be used for copy and paste operations. StringSelection stringSelection = new StringSelection(string); Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null); } public static void uploadFile(String fileLocation) { try { //Setting clipboard with file location setClipboardData(fileLocation); //native key strokes for CTRL, V and ENTER keys Robot robot = new Robot(); 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.keyRelease(KeyEvent.VK_ENTER); } catch (Exception exp) { exp.printStackTrace(); } } }
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 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 not possible or reliable with other languages (e.g. VBScript and SendKeys). AutoIt is also very small, self-contained and will run on all versions of Windows out-of-the-box with no annoying “runtimes” required!
Now the question is how we do upload file using AutoIT Tool in Selenium WebDriver.
Follow the below steps:
- We need to download the latest version of from the AutoIT Official website. you can get the link from here
- After Successful install, you can able to see the Different option in the windows startup menu.
- In Windows startup, you will get an option for “AutoIt Window Info” click on that. After click “AutoIt Window Info” a new popup window will open.
- Again goto the AutoIT official website to download the AutoIT Editor. you can download the editor from this link
- Download and Install the editor. After successful installation of the editor, you can find an option SciTE in the windows startup menu.
- Click on SciTE to open the editor so that we can write the script for upload a file.
How to Generate AutoIT Automation Script:
Until this we are know how to install AutoIT, now onwards we are going to learn how we can write the automation script so that we can automate the file uploading process.
- Open the File upload URl and click on choose file, after that keep the dialogue as it is.
- From the AutoIT Window Info window drag the Finder Tool to the required component to get the detail 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, you can refer the AutoIT built-in functions [link] page for better understand the functions use.
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 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 extension filename.au3
- If you run the script by right click on the file and select the run script, you can find that file is uploaded.
- For use in our Selenium automation script, we need to compile the save filename.au3 file, you can do that by right click on the file and choose compile script.
How to Use The AutoIT Automation Script in Selenium
Until this, we have seen how to install and preparation of 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 in case the screen resolution changes, the behaviour of Sikuli would differ. So, it is advisable to run the scripts on the same resolution of the images captured. In case, a pixel size of an image changes, it throws 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 at uploading files in your Selenium projects efficiently.
Leave a Reply