You can upload a PDF file in Playwright using the setInputFiles
method, even without a submit button.
First, locate the input element with the type "file" using the page.getByLabel()
method. Then, call setInputFiles()
on it and pass in the file paths.
Here's how you can select one file for upload:
await page.getByLabel('Upload file').setInputFiles('myfile.pdf');
For multiple files, pass an array of file paths:
await page.getByLabel('Upload files').setInputFiles(['file1.txt', 'file2.txt']);
To remove all selected files, pass an empty array:
await page.getByLabel('Upload file').setInputFiles([]);
You can also upload a buffer from memory:
await page.getByLabel('Upload file').setInputFiles({
name: 'file.txt',
mimeType: 'text/plain',
buffer: Buffer.from('this is test')
});
If the input element is created dynamically and you can't access it directly, handle the page.on('filechooser')
event. Start waiting for this event before clicking on any button that triggers it. Once triggered, handle it by calling setFiles()
on its returned object.
In summary, you can upload files in Playwright by finding and selecting files through their paths or buffers. If there's no direct access to these elements, handling events becomes necessary.
If you still have questions, please ask a question and I will try to answer it.
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 [email protected].