Selenium File Upload

How To Upload a File Using Selenium Commands

Many website applications give you the ability to upload a file or photograph, but it's not easy to write a Selenium script that automates interaction with a file upload dialog box. And while a third-party tool like AutoIt solves for this in the short-term, it can also be limiting when it comes to testing file upload functionality on different browser and OS combinations (for example, AutoIt is only available for Windows).

One solution for this problem is to bypass the dialog box entirely. This can be done by writing a Selenium script that inserts the full text name of the file that needs to be uploaded into the dialog box form field and then submitting the form.

Here's a summary of the steps you need to take to accomplish this task:

  • Include the required libraries (e.g., selenium-webdriver to automate browser interaction, and rspec/expectations & RSpec::Matchers to assert the test result) and write the setup, run, and teardown steps.
  • Write the file upload test.
  • Enter the full path to the file (e.g., File.join(Dir.pwd, filename)). Note that we’re assuming the file is located in the same directory as the test script.
  • Use a Selenium command to go to the page with the file upload form, input the full path name to the file, plus the filename with its extension) and submit the form.

Once the file is uploaded the web page will show the filename that it just processed - this text is used to assert the success of the test. This technique will work across all browsers. However, if you are using a remote instance like Sauce Labs, you should use the file_detector driver extension.

Get started with Selenium testing today and download our Selenium Bootcamp guide.