Upload a File Using Selenium WebDriver

Web application testing is not only about the on-screen functionality but also involves interacting with external resources, such as images, documents and other media.

To upload a file using Selenium, the file path is needed to be set in the input element control before submitting the form.

On the form the control to inspect should look like the image below.

Browse... No files selected

When the folder button is clicked the folder dialog is displayed by the browser.

File Upload dialog

The HTML input element should look similar to the code below.
Take note of the type="file" attribute.

<input id="fileUpload" type="file">Browse...</input>

When the Browse button is selected, The native operating system file select dialog will be opened.

This dialog will not be recognized by the Selenium WebDriver, so there is no requirement in clicking this button.

Use sendKeys on the element to set the absolute path to the file that is needed to be uploaded.

WebElement uploadInput = driver.findElement(By.id("fileUpload"));

After sendKeys has been executed, the form can be submitted.





Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.