Uploading a file with sendKeys method

The Easy way of uploading a file is simple case of just finding the element and typing the absolute path of the document into it.

It is mandatory that it works only when the textbox is enabled. So please make sure that the input element is visible. In the below example 'uploadsubmit' is the name of that element and in 'sendKeys()' we have to specify the absolute path of the content that we want to upload (that can be file/image/video etc).

Sample HTML Code should look similar to this :

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

The following is the example program to upload a file using sendKeys() in selenium webdriver without using any third party tools:

package com.easy.upload;
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";
	public void testUpload() throws InterruptedException
		driver = new FirefoxDriver();
		WebElement element = driver.findElement(By.name("uploadsubmit"));
//To input the filename along with path
// To click on the submit button (Not the browse button)
		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 browse button will open windows dialogue box where selenium webdriver will won't work. Using above code we have successfully given the file path. Now submit the form/upload and see that file has successfully uploaded.

Selenium Tutorials: 


In the UploadFile Class we have the below code
1. WebElement element = driver.findElement(By.name("uploadsubmit")); - This is used to find the element i.e Browse button in this example
2. element.sendKeys("D:/file.txt"); - This is used to send the text
3. driver.findElement(By.name("uploadSubmit")); - We are again finding the element i.e Browse Button

After finding the element in the line 1 without clicking on the Browse button how will you send the location of the file i.e in Line 2. Even though I put the code for click it is still not working. Please clarify.

Appreciate your help. Ur website is awesome :-)

Hi ranjith, for the query u posted, did u get the solution?

String checkText = driver.findElement(By.id("message")).getText();
For above statement,No id("message") element locator present in the webpage.

Add new comment