How To Upload A File In Selenium Webdriver

Hello Folks,

In this post we will learn how can we upload a file using selenium webdriver.

Sometimes we encounter scenarios where we need to upload a file to proceed further. A file upload web elements looks like as below:

You need to click on “Choose File” button which opens up File explorer and you need to select a file from desired location. This is manual process.

How to upload a file using Selenium WebDriver?

Before we learn this, first we will observe html code of file upload web element. Observe below code:

HTML code:

A file upload web element is created using “input” tag with type as “file”. An input tag is used to accept some value or user action. This input tag makes it very simple to upload a file through selenium webdriver. You just need to use sendKeys() method of selenium webdriver and send absolute path of file as argument. Let’s see an example below:

Let’s create a file upload web element in html. Save below code with some name with html extension. Say I give it name as “FileUpload.html”.

When you open in a browser, you will see File Upload web element shown above. When you click on “Choose File” button and select a file to upload, you will notice file name is shown beside “Choose File” button as below:

This means file is uploaded successfully. Now, we will see how to do the same using selenium webdriver. As discussed above, we just need to use sendKeys() method of selenium webdriver and send absolute path of file as argument.

Java code:

Output:
When you will execute above code, you will find that specified file is uploaded successfully.

If you have any doubt, feel free to comment below.
If you like my posts, please like, comment, share and subscribe.
#ThanksForReading
#HappySelenium

2 thoughts on “How To Upload A File In Selenium Webdriver

Leave a Reply

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