Saturday, September 24, 2016

How to upload a file via browse in selenium webdriver

As you know that Selenium webdriver does not support uploading of files via browse button, so we need some alternate options for it.
I am providing an alternate solution which will use robot class. Robot class is a class which works as if a user is manually clicking keyboard keys or using a mouse.

Packages to Import:
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;

import java.awt.event.KeyEvent;

Step 1: Click on browse button

Step 2: Save complete file location path to a variable. Use double forward slashes instead of single as single slashes are not supported in java.
String filepath = "C:\\Users\\sushilsingh\\image.jpg"

Step 3: Copy file location path from clipboard in a variable
public static void setClipboardData(String filepath)
{
//StringSelection is a class that can be used for copy and paste operations. Below code will copy the text from clipboard and save it in a variable.
StringSelection stringSelection = new StringSelection(filepath);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);

}

Step 4: Declare robot class
robot = new Robot();

Step 5: Now perform paste operation using robot class. We will perform ctrl + v operation using robot class. Robot needs both press and release actions for an operation to perform.
robot.keyPress(KeyEvent.VK_CONTROL);  // Pressing control (ctrl ) key
robot.keyPress(KeyEvent.VK_V);  // Pressing V key 
robot.keyRelease(KeyEvent.VK_V);  // Release V key
robot.keyRelease(KeyEvent.VK_CONTROL);  // Release control ( ctrl ) key
robot.keyPress(KeyEvent.VK_ENTER);  // Press Enter key to click on open button in browse pop-up 

robot.keyRelease(KeyEvent.VK_ENTER);  // Release Enter key to click on open button in browse pop-up

The above steps will perform a file upload operation via browse button.

If you still face any issue, please write in comments section