How to upload file in Selenium WebDriver using sendKeys() method

Let us talk about how to upload file in Selenium WebDriver. We can upload the file in selenium WebDriver using various methods. By using sendKeys() method is one of the simplest one.
Upload file in Selenium WebDriver using sendKeys
This is the simplest way to upload the file in selenium Webdriver. Here we will use sendKeys() method to send the absolute file path to be uploaded. But this can be achieved only when the type attribute for filepath textbox / browse button is “file”. Observe below screenshot for this.
As in above screenshot, since type = file, we can use sendKeys() method to send the file path & then click on upload / submit file button to complete upload process.
First make sure that the input element is visible
Don’t click on the browse button, it will trigger an OS level dialogue box and effectively stop your test dead.
Instead you can use:
driver.findElement(By.xpath(“//*[@id=’uploadfile_0′]”)).sendKeys(“C:UsersPrakashDesktopDesktopTOSCA tutorial.pptx”);
//*[@id=’uploadfile_0′] is the xpath of that element (button in this case) and in sendKeys you have to specify the absolute path of the content you want to upload (Image,video etc). Selenium will do the rest for you.
Keep in mind that the upload file will work only If the element you send a file should be in the form    <input type=”file”>
Below is the sample example of how to upload file –

package basicsOfSelenium;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class FileUploadInSelenium1 {

 public static void main(String[] args) {

  WebDriver driver = new FirefoxDriver();
  driver.navigate().to("http://demo.guru99.com/selenium/upload/");
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  driver.manage().window().maximize();
  
  //send the file path to be uploaded to the element, note - this will work only if attribute type = file
  driver.findElement(By.xpath("//*[@id='uploadfile_0']")).sendKeys("C:UsersPrakashDesktopDesktopTOSCA tutorial.pptx");
  
  //click on accept term checkbox
  driver.findElement(By.xpath("//*[@id='terms']")).click();
  //click on submit button - to complete file upload
  driver.findElement(By.xpath("//*[@id='submitbutton']")).click();

  
 }

}
Well, this was all about upload file in Selenium webdriver by using sendKeys() method. There is another way to do it is by using AutoIT. Refer below link to know more about AutoIT

AutoIT Tutorials – Upload and download files in Selenium WebDriver

Hope this helps !!!

Leave Comment

Your email address will not be published. Required fields are marked *

Looking for learning Framework Development from Scratch? Lookout for Detailed Framework Development videos on YouTube here -

https://www.youtube.com/automationtalks

Get the Framework code at Github Repo: https://github.com/prakashnarkhede?tab=repositories