Chapter 13 :File uploading and downloading

File uploading:

file uploading in selenium Webdriver is perform by simply using the sendKeys() method on the file-select input field to enter the path to the file to be uploaded.Get the file upload element either by using the Id or Name. 

Lets go through following html code:

<html>
<body>
<form enctype="form-data" action="parse_file.php" method="post"> 
  <p>Browse for a file to upload: </p>
  <input type="file" name="uploadsubmit">
  <br/><br/>
  <input type="submit" value="SUBMIT">
</form>
</body>
</html>

Output of above code:

Remember the two things when uploading files in WebDriver

  1. There is no need to simulate the clicking of the “Browse” button. WebDriver automatically enters the file path onto the file-selection text box of the <input type=”file”> element
  2. When setting the file path in your Java IDE, use the proper escape character for the back-slash.

Complete webdriver code:

package testology;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
public class fileupload
   {
static WebDriver driver;
String URL = "file:///C:/Users/admin/Documents/selenium/html%20example/fileupload.html";
	@Test
	public void testUpload() throws InterruptedException
	   {
	driver = new ChromeDriver();
	driver.get(URL);
WebElement element = driver.findElement(By.name("uploadsubmit"));
//To input the filename along with path
element.sendKeys("C:\\Users\\admin\\Desktop/file.txt");
// To click on the submit button (Not the browse button)
driver.findElement(By.cssSelector("input[type='submit'][value='SUBMIT']")).click();
		
}	
}

Downloading Files:

WebDriver has no capability to access the Download dialog boxes presented by browsers when you click on a download link or button.