Monday, 8 February 2016

Selenium:file uploading using sendKeys()

Selenium:file uploading using sendKeys():
==================================
We can upload a file using sendKeys() method as well.
We can sendKeys() when ever that element contains type=file then only we can use sendKeys() method.

Even we can upload a file using Robot class as well.

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



FileUploadDemo.java:
----------------------
package testngdemo;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class FileUploadDemo {

WebDriver driver;

@BeforeTest
public void openBrowser() {
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().implicitlyWait(45, TimeUnit.SECONDS);
}

@Test
public void testUpload() throws InterruptedException {

driver.get("file:///C:/Users/aramesh/Desktop/fileupload.html");
WebElement element = driver.findElement(By.name("upload"));
element.sendKeys("C:\\Users\\ramesh\\Desktop\\abc.txt");

}

@AfterTest
public void closeBrowser() {
driver.quit();

}
}

No comments:

Post a Comment