What is the method to upload multiple files using Playwright?


Uploading Files with Playwright

Uploading files in Playwright is a breeze with the setInputFiles() method. This method works with an input element of type "file". You can select multiple files by passing them in an array. For example:

await page.getByLabel('Upload files').setInputFiles(['file1.txt', 'file2.txt']);

To deselect all files, pass an empty array:

await page.getByLabel('Upload file').setInputFiles([]);

If your input element is created dynamically, you can handle the page.on('filechooser') event or use a waiting method. Here's how:

const fileChooserPromise = page.waitForEvent('filechooser');
await page.getByLabel('Upload file').click();
const fileChooser = await fileChooserPromise;
await fileChooser.setFiles('myfile.pdf');

For pages that handle focus events, Playwright lets you focus on specific elements with locator.focus(). Like so:

await page.getByLabel('Password').focus();

And if you need to upload a buffer from memory, setInputFiles() has got you covered. Just provide a name, MIME type, and content as a Buffer object:

await page.getByLabel('Upload file').setInputFiles({
  name: 'file.txt',
  mimeType: 'text/plain',
  buffer: Buffer.from("this is test")

With these tips, you'll master file uploads in your Playwright tests in no time. 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.