All challenges · Advanced Techniques
Challenge 19 of 29 · Stretch skills · Advanced Techniques
Upload a File
Attach a file to an upload field without the operating system picker, using a file name only known at run time, then submit the form.
Skills you will practise
- setInputFiles
- in-memory files
- form submission
The concept
Clicking an upload button normally opens the operating system's file picker, which a browser test cannot drive. Playwright skips it: locator.setInputFiles() attaches files directly to an <input type="file">, and the page receives them as if the user had picked them.
You can pass a path to a real file, an array of paths, or an in-memory file described with a name, mimeType and buffer. In-memory files are handy when the file name or content has to be unique per run, and they keep tests free of fixture files.
After attaching, submit the form and assert on what the page shows, such as the file name in a confirmation.
The fragile version
await page.getByRole('button', { name: 'Choose file' }).click();
// ...test hangs waiting for a native dialog it cannot controlWhy it breaks: Clicking opens the native picker, which Playwright does not automate. The test has no way to choose a file.
A robust Playwright version
const fileName = `report-${Date.now()}.txt`;
await page.getByLabel('Attachment').setInputFiles({
name: fileName,
mimeType: 'text/csv',
buffer: Buffer.from('hello'),
});
await page.getByRole('button', { name: 'Attach report' }).click();
await expect(page.getByText(fileName)).toBeVisible();The file is attached directly to the input with a run-time name, and the test checks the upload was received.
This is a general example on a made-up page, not the challenge’s reference solution.
Common mistakes
- Clicking the button that opens the native picker.
- Calling
setInputFileson a styled wrapper instead of the actual file input. - If you must click, not using
page.waitForEvent('filechooser')before the click.
FAQ
How do I upload a file in Playwright?
await locator.setInputFiles(pathOrFile) on the file input.
Can I upload without a real file on disk?
Yes, pass { name, mimeType, buffer }.
How do I clear selected files?
await locator.setInputFiles([]).
Try it
Practise this in Challenge 19. You write the code in the browser editor with no setup. It runs in a fresh Chromium, a hidden validator checks what actually happened, and you get pass or fail, the logs and a video of the run. Create a free account to open the practice page and its hints. The reference solution and the hidden validator are shown only after you pass. We never publish solutions here.