Upload File using Selenium sendKeys() Method
Upload File using Selenium sendKeys() Method
The simplest way to upload a file is by locating the element and entering the absolute path of the file into it.
However, this method works only if the input field is enabled and visible. Ensure that the element is displayed before proceeding. In the example below, 'uploadfile'
is the name of the input element, and the absolute path of the file to be uploaded is specified in the sendKeys()
method.
Sample HTML Code
Sample HTML Code should look similar to this :
<html>
<body>
<form enctype="multipart/form-data" action="process_file.php" method="post">
<p>Browse for a file to upload: </p>
<input type="file" name="uploadfile"> <br/>
<input type="submit" value="SUBMIT">
</form>
</body>
</html>
Sample Selenium Code
The following is the example program to upload a file using sendKeys() in Selenium webdriver without using any third-party tools:
package com.testingdocs.tutorials;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.Test;
public class UploadFile {
static WebDriver driver;
String URL = "application URL";
@Test
public void testUpload() throws InterruptedException
{
driver = new FirefoxDriver();
driver.get(URL);
WebElement element = driver.findElement(By.name("uploadfile"));
//To input the filename along with path
element.sendKeys("C:/upload.txt");
// To click on the submit button (Not the browse button)
driver.findElement(By.name("SubmitBtn")).click();
String checkText = driver.findElement(By.id("message")).getText();
Assert.assertEquals("File uploaded successfully", checkText);
}
}
Make sure, you are not clicking on the browse button, clicking on the browse button will open the Windows dialogue box where Selenium webdriver will won’t work.