How to Upload a File in Playwright
You might encounter a scenario on how to upload a File in Playwright. To do that you can make use of the ‘filechooser’ event. You can also make use of setInputFiles method available in locator class but that only works when you have an ‘input’ element with the type ‘file’.
The other best alternative is via ‘filechooser’ which behaves just like an event like ‘page’. You can use file chooser event in multiple ways. One of the easiest ways is to use it using Promise.all which will wait for the attach event click and then wait till it meets the filechoose event.
Don’t worry I have given you the exact code and explained it in a very simple way below.
When there is no Input Element – How to Upload a File in Playwright
The following piece of code will help you understand how to upload a file in Playwright if you do not have the input element in your DOM.
const [fileChooser] = await Promise.all([
page.waitForEvent('filechooser'),
page.locator('locator info here').click()
]);
await fileChooser.setFiles('file.txt');
NOTE: Make sure the file.txt is located in your project folder or you will get an error of file not found. You can also alternatively specify the path.
In the third line of the above code, you can see the locator that triggers the attachment window has to be clicked. So the first thing that Playwright does is wait for the click to happen and then will continue to wait for the event ‘filechooser’. Once it recognizes the file uploader, it will come out of the promise.
The bottom line is where the file will be actually chosen. As mentioned earlier make sure you add a valid existing file or you might encounter the following error:
Error: ENOENT: no such file or directory, stat
If Input Element is Available
If you have the ‘input’ element readily available in the DOM, you can alternatively also use what Playwright suggests:
const fileChooserPromise = page.waitForEvent('filechooser');
await page.getByText('Upload file').click();
const fileChooser = await fileChooserPromise;
await fileChooser.setFiles('myfile.pdf');
The above will work as well.
Let me know if the above solutions on how to upload a file in Playwright helped. For more content on Playwright check the Testing> Automation > Playwright category on our website.