Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to upload file using Selenium WebDriver in Java

Can anyone let me know how to upload a file using Selenium by Java code?

When I click on button in the application it gets open in the new window what I can use to select upload file. The browse button developed by Silverlight (C#).

like image 916
Mahesh Avatar asked Jun 03 '13 12:06

Mahesh


People also ask

How do I automate a file to upload?

You can call sendKeys() on the file control to fill the file control with file path and then submit form. With this approach, no file dialog will be shown, you just bypass the file dialog and set the file path directly in the file upload control.

Does Selenium support upload?

We can upload files to the browser with the help of Selenium webdriver. This is done with the help of sendKeys() method on the element which does the selection of the file by specifying the path of the file to be uploaded. While working on file upload functionality, we need to click on the Browse button.


2 Answers

First make sure that the input element is visible

As stated by Mark Collin in the discussion here:

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.id("myUploadElement")).sendKeys("<absolutePathToMyFile>");

myUploadElement is the id 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 will work only If the element you send a file should be in the form <input type="file">

like image 129
Kedar T Avatar answered Sep 22 '22 17:09

Kedar T


driver.findElement(By.id("urid")).sendKeys("drive:\\path\\filename.extension"); 
like image 43
Neopane Avatar answered Sep 24 '22 17:09

Neopane