Uploading Files with Selenium for Java
Uploading Files with Selenium for Java
Learn how to upload a file in Selenium for Java
The HTML File Picker widget is a way to allow users to upload specific files to a website.
For example, if I wanted to upload a picture of my world-famous mac and cheese, I could do so by clicking this Choose File button, selecting the image, and pressing Open.
And notice the file is uploaded. Whew, doesn’t that look great?
However, this popup window for the Choose File button cannot be accessed from Selenium WebDriver.
How to Access File Upload Options with Selenium
To accomplish this within our Selenium test, we’ll need to bypass the popup window altogether. Let me show you how.
First, we’ll need the absolute filePath to the file we want to upload.
You don’t want the relative path, nor do you want just the file name, you need the absolute path to this file for this to work.
Next, we’re going to use our Selenium driver object to find that file input element on the website, using findElement(). Let’s go and grab the ID. Notice this input element, with type file. This is the one we need.
So, I’ll grab this ID and paste it into our code — driver.findElement(By.id(“photo-upload”)).
Now that we have the file upload element, we want to .sendKeys(filePath) and we’re going to send that absolute filePath.
And that’s it, this will give us the same result as if we went through the popup window.
Resources
- Git Repo – FileUploadTests.java
- Applitools Kitchen – File Upload Testing
Schedule a free Applitools Demonstration
Request DemoHere’s the code sample from our tutorial on how to upload a file in Selenium for Java