How to upload files with Playwright

profile
Tim Deschryver
timdeschryver.dev

This post shows you how to upload files with Playwright. To keep it basic, let's just take a page with a simple upload input element, and let's also show the filename after it's been uploaded.

As usual, I start writing my Playwright test by starting the codegen tool. Because I installed the Playwright extension for Visual Studio Code, I can quickly start the codegen tool via the command palette.

Let's take a look at the codegen tool in action to upload a file.

The process of using the codegen tool while I upload a file.

When we're done with the codegen tool, we end up with a new test file and the following generated code. I already highlighted the most important lines.

As we can see in the generated test, we can use the page.setInputFiles method to upload one or more files.

So far so good, but when you run the test, you probably get the following error.

The error says that the file that we want to upload doesn't exist. If we take a closer, we can notice that the codegen tools only sets the filename of the uploaded file, not the path to the file. Because of this, the file cannot be found while the test is running.

To fix this problem, change the test so that it uses a relative path (starting from the root of the project) to the file.

I like to create a fixtures folder inside the tests folder for generic files that I want to use in my tests. Specific files for a test can be added right next to the test file, which makes it obvious that it's specific to a test.

The modified test looks like this.

After this change, the test passes. More importantly, we've seen how to upload files with Playwright.

Outgoing links

Feel free to update this blog post on GitHub, thanks in advance!

Join My Newsletter (WIP)

Join my weekly newsletter to receive my latest blog posts and bits, directly in your inbox.

Support me

I appreciate it if you would support me if have you enjoyed this post and found it useful, thank you in advance.

Buy Me a Coffee at ko-fi.com PayPal logo

Share this post on

Twitter LinkedIn