Handle Files Upload, Drag & Drop

Handle File Upload using Selenium Webdriver 

Files are uploaded using the sendKeys() method on the file-select field where the path of the file should be passed. It’s the most basic technique to perform the upload of a file. There is no need to simulate the clicking of browse button. Ensure use of the proper escape character for the back-slash while setting the file path.

Example : Let’s try automating a file upload in our site https://demoapp1.tequality.tech

Handle File Upload using Selenium Webdriver Example

driver.findElement(By.xpath("//input[@type='file']")).sendKeys("E://Selenium//Selenium.png");

 

Handle Drag & Drop using Selenium Webdriver

This action is performed with a mouse by moving (drags) a web element from one location and places (drops) it into an alternate location. By using Action class which has a method available in selenium webdriver this can be achieved.

Syntax: Actions.dragAndDrop(Sourcelocator, Destinationlocator)

Here, “Sourcelocator” is the element which we need to drag
And “Destinationlocator” is the element on which we need to drop the first element

Steps to follow:

First, instantiate an Actions class: 
Actions actions = new Actions(driver);

Second, find the source locator and destination locator and then perform drag and drop operation
actions.dragAndDrop(source,target).perform();


Internally below commands get executed:

  • Click And Hold Action: This method click-and-hold the location of the source element
  • Move Mouse Action: By this method source element gets moved to the location of the target element
  • Button Release Action: Through this mouse is released
  • Build: This method generates a composite action containing all actions. This get executed in the perform method internally
  • Perform: This method performs the actions we have specified. First it internally invokes build() method and after that the action is performed

Test code for Drag and drop is covered in last section