How do I upload files in Playwright?


Uploading Files with Playwright

Uploading files in Playwright is a breeze! You can use the setInputFiles() method. This method needs the first argument to be an input element with the type "file". You can select one or multiple files by passing in an array of file paths. If some of the file paths are relative, they are resolved relative to the current working directory. To remove all selected files, pass an empty array as an argument.

await page.setInputFiles('input[type=file]', ['/path/to/file']);

Sometimes, you might not have access to the input element in your code. Don't worry! You can handle the page.on('filechooser') event or use a corresponding waiting method upon your action. For example, you can start waiting for a file chooser before clicking on a button that triggers it and then set its files once it appears.

const [fileChooser] = await Promise.all([
  page.click('#upload-button'), // some button that triggers file selection
await fileChooser.setInputFiles('/path/to/file');

Did you know you can also upload a buffer from memory using setInputFiles()? Instead of passing in an array of file paths as an argument, pass in an object with properties such as name (the name of the file), mimeType (the MIME type of the content), and buffer (a Buffer containing the content).

await page.setInputFiles('input[type=file]', {
  name: 'myfile.txt',
  mimeType: 'text/plain',
  buffer: Buffer.from('Hello world')

That's it! Uploading files using Playwright is straightforward and flexible enough to accommodate various scenarios. Happy testing!


Thank you!
Was this helpful?
Still have questions?

If you still have questions, please ask a question and I will try to answer it.

Related Questions

AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email luc@ray.run.