How To Use Java Robot To Upload File In Selenium Webdriver

Uploading files is a common task in web-based applications. It is not easy to implement in selenium WebDriver automation, because the upload file component will popup a select file dialog that can not be handled by the selenium WebDriver. But java.awt.Robot provide a method to interact with OS native window dialog, this article will show you examples about how to use java.awt.Robot to select upload file in selenium WebDriver automation script.

1.Use java.awt.Robot To Upload File Example In Firefox, IE, and Chrome.

  1. Below is the example Html web page that contains the Upload File button.
    firefox-upload-file-input-component
  2. Below is the example java source code, the java file name is TestUploadFileWithRobot.java.
    public class TestUploadFileWithRobot {
    
    	public static void main(String[] args) {
    
    		TestUploadFileWithRobot example = new TestUploadFileWithRobot();
    		
    		example.uploadFileFirefox();
    
    		example.uploadFileIE();
    		
    		example.uploadFileChrome();
    
    	}
    	
    	/* Upload in Firefox. */
    	public void uploadFileFirefox()
    	{
    		WebDriver driver = null;
    		try
    		{	
    			// Create FirefoxDriver object.
    			driver = new FirefoxDriver();
    			
    			this.uploadFile(driver);
    			
    		}catch(Exception ex)
    		{
    			ex.printStackTrace();
    		}finally
    		{
    			if(driver!=null)
    			{
    				driver.close();
    				driver = null;
    			}
    		}
    	}
    	
    	/* Upload in Chrome. */
    	public void uploadFileChrome()
    	{
    		ChromeDriver driver = null;
    		try
    		{	
    			 // Specify Chrome Driver executable file 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();
    			
    			this.uploadFile(driver);
    			
    		}catch(Exception ex)
    		{
    			ex.printStackTrace();
    		}finally
    		{
    			if(driver!=null)
    			{
    				driver.close();
    				driver = null;
    			}
    		}
    	}
    	
    	/* Upload in Internet Explorer. */
    	public void uploadFileIE()
    	{
    		InternetExplorerDriver driver = null;
    		try
    		{	
    			// Define ieDriver execute file path.
    			String ieDriverFilePath = "C:\\Workspace\\dev2qa.com\\Lib\\IEDriverServer_x64_3.4.0\\IEDriverServer.exe";
    			
    			//Specify ie executable file path to sysem property.
    			System.setProperty("webdriver.ie.driver", ieDriverFilePath);
    			
    			//Initiate internet explorer driver
    			driver = new InternetExplorerDriver();
    			
    			this.uploadFile(driver);
    			
    		}catch(Exception ex)
    		{
    			ex.printStackTrace();
    		}finally
    		{
    			if(driver!=null)
    			{
    				driver.close();
    				driver = null;
    			}
    		}
    	}
    	
    	/* This is the common method that implement file upload action. */
    	public void uploadFile(WebDriver driver)
    	{		
    		try
    		{
    			/* Upload file page*/
    			String uploadFileDisplayUrl = "http://www.dev2qa.com/demo/upload/uploadFileTest.html";
    						
    			// Display above page.
    			driver.get(uploadFileDisplayUrl);
    			
    			//Get the upload file web element by it's name "uploadFileInputBox"
    			WebElement element = driver.findElement(By.name("uploadFileInputBox"));
    			
    			//Click the Browse button to open select file window.
    			element.click();
    			
    			Thread.sleep(1000);
    			
    			// Get Robot Object.
    			Robot robotObj = new Robot();
    			
    			// This is the upload file directory, it should be exist.
    			String uploadFileDir = "C:/Workspace";			
    			// Navigate to upload file located directory input text box.
    			this.pressTabKey(robotObj, 4);
    			// Copy file directory.
    			this.copyStringToTargetInputBox(robotObj, uploadFileDir);
    			
    			// This is the upload file name, it should be exist also.
    			String uploadFile = "uploadFileTest.txt";
    			// Click tab key six time to goto upload file input text box.
    			this.pressTabKey(robotObj, 6);
    			// Copy file name
    			this.copyStringToTargetInputBox(robotObj, uploadFile);
    			
    			
    			// Navigate to Open button.
    			this.pressTabKey(robotObj, 2);
    			// Click the Open button.
    			this.pressEnterKey(robotObj);
    			
    			// Click the form submit button. 
    			driver.findElement(By.name("uploadFileSubmitBtn")).click();
    			
    			Thread.sleep(3000);
    			
    			//Get the return message in the returned web page. 
    			String checkText = driver.findElement(By.id("returnMessage")).getText();
    			
    			//Check whether the action success or fail by verify the return message.
    			if("Your file has been uploaded successful".equals(checkText))
    			{
    				System.out.println("Upload file success.");
    			}else
    			{
    				System.out.println("Upload file fail.");
    			}
    		}catch(Exception ex)
    		{
    			ex.printStackTrace();
    		}
    	}
    	
    	/* This method use Robot and system clipboard to copy text to the input text box.*/
    	private void copyStringToTargetInputBox(Robot robot, String text) throws InterruptedException
    	{
    		// First copy text to system clipboard.
    		StringSelection stringSel = new StringSelection(text);
    		Toolkit tk = Toolkit.getDefaultToolkit();
    		Clipboard cb = tk.getSystemClipboard();
    		cb.setContents(stringSel, stringSel);
    
    		// Press enter to make it focus before copy text to it.
    		this.pressEnterKey(robot);
    		
    		// Copy the text from system clipboard to input text box.
    		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);
    
    	}
    	
    	/* Implement press enter key keyboard action.*/
    	private void pressEnterKey(Robot robotObj) throws InterruptedException
    	{
    		robotObj.keyPress(KeyEvent.VK_ENTER);
    		robotObj.keyRelease(KeyEvent.VK_ENTER);
    		
    		Thread.sleep(1000);
    	}
    	
    	/* Implement press tab key keyboard action.*/
    	private void pressTabKey(Robot robotObj, int pressCount) throws InterruptedException 
    	{
    		for(int i=0;i<pressCount;i++)
    		{
    			Thread.sleep(2000);
    			robotObj.keyPress(KeyEvent.VK_TAB);
    		}
    	}
    }
    

References

  1. java.awt.Robot
  2. java.awt.event.KeyEvent
  3. java.awt.event.InputEvent

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.