Back to All Questions
Question 85 of 100
Interactions
Intermediate
How do you handle file uploads and downloads?
The Answer
For uploads, use `page.setInputFiles()` on the file input element. For downloads, listen for the `download` event with `Promise.all()` before triggering the download action.
Deep Dive Explanation
The `Promise.all()` pattern for both file chooser and download is critical β register the event listener before triggering the action to avoid race conditions. The `setInputFiles()` approach bypasses the OS file picker dialog entirely, making it reliable in CI.
example.spec.ts
// FILE UPLOAD - Standard input
await page.locator('input[type="file"]').setInputFiles('tests/fixtures/resume.pdf');
// Multiple files
await page.locator('input[type="file"]').setInputFiles([
'tests/fixtures/doc1.pdf',
'tests/fixtures/doc2.pdf',
]);
// Upload via file chooser dialog (for custom upload buttons)
const [fileChooser] = await Promise.all([
page.waitForEvent('filechooser'),
page.getByRole('button', { name: 'Upload File' }).click(),
]);
await fileChooser.setFiles('tests/fixtures/resume.pdf');
// FILE DOWNLOAD
const [download] = await Promise.all([
page.waitForEvent('download'),
page.getByRole('button', { name: 'Export CSV' }).click(),
]);
const path = await download.path();
await download.saveAs('./downloads/' + download.suggestedFilename());
console.log('Downloaded:', download.suggestedFilename());