| Photo by Caspian Dahlström |
How to upload files using Playwright?
To upload files in Playwright, there are two ways,
- Using the 'page.setInputFiles(selector, files[, options])' method on the page.
- Using 'page.on('filechooser')' event.
To upload files using 'setInputFiles(selector, files[, options])' method selector expected to be an input element with the type "file". Second parameter files accept the array of paths of the files. Files can be multiple and different file types as well.
Element example:
<input accept="video/*,mage/*" id="upload" type="file"> Above element could be selected as 'input[type='file']'.
// Select one file
await page.setInputFiles('input#upload', 'myfile.pdf');
// Select multiple files
await page.setInputFiles('input#upload', ['file1.txt', 'file2.txt']);
// Remove all the selected files
await page.setInputFiles('input#upload', []);
// Upload buffer from memory
await page.setInputFiles('input#upload', {
name: 'file.txt',
mimeType: 'text/plain',
buffer: Buffer.from('this is test')
});
If an element with the input tag is not present or a file chooser window is popping up when clicked on an element 'filechooser' event can be used. It works on all operating systems.
const [fileChooser] = await Promise.all([
page.waitForEvent('filechooser'),
page.click('upload')
]);
await fileChooser.setFiles('myfile.pdf');
File uploading in playwright is not working properly on Chrome/Chromium for video files, Firefox is recommended in case of any trouble while uploading.