Skip to main content

How to Upload a File

The Problem

Uploading a file is a common piece of functionality found on the web but when trying to automate it, you get prompted with a dialog box that is just out of reach of your automation script.

In these cases people often look to a third-party tool to manipulate this window (e.g., AutoIt). While this can help solve your short-term need, it sets you up for failure later by chaining you to a specific platform (e.g., AutoIt only works on Windows), effectively limiting your ability to test this functionality on different browser & operating system combinations.

A Solution

A work-around for this problem is to side-step the system dialog box entirely. We can do this by inserting the full path of the file we want to upload (as text) into the form and then submit the form.

Let's step through an example.

Example

NOTE: We are using a file upload example found on the-internet.

Expected Behavior

After executing the test, this is what will happen:

  • Open the browser
  • Visit the upload form page
  • Inject the file path into the form and submit it
  • Page displays the uploaded filename
  • Grab the text from the page and assert it's what we expect
  • Close the browser

Outro

This approach will work across all browsers. If you want to use it with a remote instance (e.g., on Selenium Grid or Sauce Labs) then you'll want to have a look at remote uploads.

Happy Testing!

Special Thanks

Mike Millgate
Contributed the Python code for this tip.
Isaul Vargas
Python code review
Peter Bittner
Python code review
Jonathan Taylor
Contributed the initial C# code for this tip.
Manoj Kumar
Contributed the initial JavaScript code for this tip.
Roman Isko
Contributed the initial Java code for this tip.
Andrei Solntsev
Contributed the Selenide code for this tip.

Authors

Dave Piacente
Original creator of Elemental Selenium
Diego Molina
Current maintainer of Elemental Selenium