Playwright 18 ๐ญ File Downloads and Uploads โ Handling file system interactions
Web applications routinely exchange files with their users: exporting reports as CSV or PDF, uploading avatars and documents, downloading invoices, and importing data. Testing these flows requires more than clicking a buttonโit demands capturing the file that the browser produces, verifying its contents, and supplying files that the browser consumes. Playwright treats downloads as events and uploads as input assignments, giving tests direct access to the file system without ever touching the operating system’s native file dialog.
This chapter covers both directions of file interaction. It explains how to capture downloads with waitForEvent('download'), save them with saveAs(), and read their contents; how to upload files through setInputFiles() on visible or hidden inputs; how to handle applications that trigger a native file chooser through custom buttons; and how to construct virtual files in memory when no fixture exists on disk. It also covers multi-file uploads, clearing selections, and the acceptDownloads context option. By the end, you will be able to test any file exchange flow without brittle workarounds.
Key point: Playwright never automates the operating system’s file dialog. Downloads are captured as events with a saveAs() method, and uploads are performed by assigning file paths or buffers directly to the input elementโwhether the input is visible, hidden, or only reachable through a file chooser event.
Why file handling exists in Playwright
The dialog problem. Traditional browser automation tools struggle with native file dialogs because the dialog is an operating system window, not a DOM element. Playwright sidesteps the dialog entirely: setInputFiles() assigns files to the <input type="file"> element programmatically, bypassing the click that would open the dialog. For applications where no input is reachable, the filechooser event captures the dialog request and injects the file before the native window ever appears.
The ephemeral download problem. A downloaded file lands in a temporary directory that Playwright deletes when the browser context closes. If a test wants to inspect the fileโverify its contents, check its size, or re-upload it to another pageโit must call saveAs() before the context ends. Downloads are events, not files on disk by default; the test decides whether to persist them.
The fixture problem. Upload tests need files, but committing binary fixtures to a repository is inconvenient, and some tests need content generated at runtime. Playwright accepts both: a path to a file on disk, or an in-memory FilePayload with a name, mimeType, and buffer. The buffer approach eliminates fixtures entirely for tests that can construct their own content, such as CSV strings or JSON payloads.
a. Capturing and saving downloads
A download begins when the browser receives a response with a Content-Disposition: attachment header or when a link with the download attribute is clicked. Playwright emits a download event at that moment. The event must be awaited before the action that triggers it; otherwise the event fires before a listener exists.
import { test, expect } from '@playwright/test';
test('downloading a report and verifying its contents', async ({ page }) => {
await page.goto('/reports');
// Start waiting for the download BEFORE clicking; no await here
const downloadPromise = page.waitForEvent('download');
// Trigger the download
await page.getByRole('button', { name: 'Export CSV' }).click();
// Await the event; this resolves once the download starts
const download = await downloadPromise;
// Save the file to a known path before the context closes
const savedPath = './test-results/report.csv';
await download.saveAs(savedPath);
// Verify the suggested filename matches what the server intended
expect(download.suggestedFilename()).toBe('report.csv');
// Read and assert on the file contents
const content = fs.readFileSync(savedPath, 'utf-8');
expect(content).toContain('Order ID,Total');
});
The suggestedFilename() method returns the name the browser computed from the Content-Disposition header or the download attribute . It is not the temporary GUID filename that Playwright assigns internally. If the test only needs the file’s contents, download.createReadStream() provides a readable stream without writing to disk, but saveAs() is the simplest path when the file must persist or be re-uploaded.
Downloads require the browser context to allow them. In Playwright Test, acceptDownloads defaults to true, but in standalone scripts the context must be created with { acceptDownloads: true } .
b. Uploading files to an input element
The setInputFiles() method assigns one or more files to an <input type="file"> element. It accepts a path string, an array of paths for multi-file inputs, an object with name, mimeType, and buffer for in-memory files, or an empty array to clear the selection . The input does not need to be visible; Playwright locates it by label, role, or CSS selector and sets its files programmatically.
test('uploading a document from disk', async ({ page }) => {
await page.goto('/documents');
// Locate the input by its associated label and set a file path
await page.getByLabel('Upload document').setInputFiles('./fixtures/contract.pdf');
// For a multi-file input, pass an array
await page.getByLabel('Upload attachments').setInputFiles([
'./fixtures/photo.jpg',
'./fixtures/notes.txt',
]);
// Clear the selection by passing an empty array
await page.getByLabel('Upload document').setInputFiles([]);
});
test('uploading a virtual file without touching the disk', async ({ page }) => {
await page.goto('/import');
// Construct the file entirely in memory
await page.getByLabel('Import CSV').setInputFiles({
name: 'users.csv', // filename the app will see
mimeType: 'text/csv', // MIME type for validation
buffer: Buffer.from('name,email\nAlice,alice@example.com'), // contents
});
// The application processes it exactly as if it were a real file
await expect(page.getByText('users.csv')).toBeVisible();
});
The in-memory approach is particularly valuable for tests that verify validation logic: an oversized file can be created with Buffer.alloc(6 * 1024 * 1024) to test a 5 MB limit, or a file with an invalid extension can be constructed with a mimeType of application/octet-stream and a .exe name . No fixtures need to be committed, and the test is self-documenting about what condition it exercises.
c. Handling file chooser dialogs
Some applications do not expose a visible <input type="file">. A custom button triggers input.click() through JavaScript, opening the native file picker. Playwright cannot interact with the operating system dialog, but it can intercept the filechooser event that the page emits just before the dialog would open. The event handler receives a FileChooser object whose setFiles() method accepts the same arguments as setInputFiles() .
test('uploading through a custom button that opens a file chooser', async ({ page }) => {
await page.goto('/profile');
// Start waiting for the filechooser event BEFORE the click
const fileChooserPromise = page.waitForEvent('filechooser');
// Click the custom button that triggers the native dialog
await page.getByRole('button', { name: 'Change avatar' }).click();
// The dialog request is captured; inject the file before it opens
const fileChooser = await fileChooserPromise;
// Check whether the chooser accepts multiple files
console.log('Multiple allowed:', fileChooser.isMultiple());
// Provide the file, same API surface as setInputFiles
await fileChooser.setFiles('./fixtures/avatar.png');
// The avatar preview updates; assert it
await expect(page.getByRole('img', { name: 'Avatar preview' })).toBeVisible();
});
The fileChooser.isMultiple() method indicates whether the underlying input accepts multiple files, which is useful for conditionally testing multi-file workflows . The fileChooser.element() method returns the associated input element for cases where the test needs to inspect its accept attribute or other properties . Prefer setInputFiles() when a reachable input exists; the file chooser event is the fallback for when the markup forces it .
Complete Example Session
// ============================================
// PART 1: IMPORTS AND TEST SETUP
// ============================================
import { test, expect } from '@playwright/test';
import fs from 'fs';
import path from 'path';
// ============================================
// PART 2: DOWNLOADING A FILE
// ============================================
test('complete file workflow', async ({ page }) => {
await page.goto('/documents');
// Register the download wait before the action
const downloadPromise = page.waitForEvent('download');
await page.getByRole('button', { name: 'Download template' }).click();
const download = await downloadPromise;
// ============================================
// PART 3: SAVING AND VERIFYING THE DOWNLOAD
// ============================================
const savePath = path.join('test-results', download.suggestedFilename());
await download.saveAs(savePath);
// Verify the file exists and has content
const stats = fs.statSync(savePath);
expect(stats.size).toBeGreaterThan(0);
expect(download.suggestedFilename()).toBe('template.csv');
// ============================================
// PART 4: RE-UPLOADING THE DOWNLOADED FILE
// ============================================
await page.goto('/import');
await page.getByLabel('Upload completed template').setInputFiles(savePath);
// ============================================
// PART 5: UPLOADING A VIRTUAL FILE
// ============================================
await page.goto('/import');
await page.getByLabel('Upload data').setInputFiles({
name: 'data.csv',
mimeType: 'text/csv',
buffer: Buffer.from('id,name\n1,Alice\n2,Bob'),
});
// ============================================
// PART 6: VERIFYING THE UPLOAD PREVIEW
// ============================================
await expect(page.getByText('data.csv')).toBeVisible();
await expect(page.getByText('2 rows')).toBeVisible();
// ============================================
// PART 7: CLEARING THE SELECTION
// ============================================
await page.getByLabel('Upload data').setInputFiles([]);
await expect(page.getByText('data.csv')).not.toBeVisible();
// ============================================
// PART 8: HANDLING A FILE CHOOSER
// ============================================
await page.goto('/profile');
const chooserPromise = page.waitForEvent('filechooser');
await page.getByRole('button', { name: 'Upload photo' }).click();
const chooser = await chooserPromise;
await chooser.setFiles({
name: 'photo.jpg',
mimeType: 'image/jpeg',
buffer: Buffer.from('fake-image-bytes'),
});
// ============================================
// PART 9: ASSERTING THE RESULT
// ============================================
await expect(page.getByRole('img', { name: 'Photo preview' })).toBeVisible();
// ============================================
// PART 10: CLEANUP
// ============================================
fs.unlinkSync(savePath); // remove the downloaded file from disk
});
The ten parts above cover the full lifecycle: capturing a download, persisting it, verifying its metadata and contents, re-uploading it to a different page, constructing a virtual file, clearing a selection, intercepting a file chooser, and cleaning up the saved file. The downloaded file and the uploaded file are the same data flowing in both directions, which is often the most realistic test of a document management workflow.
Quick Reference
Download Methods
| Method | Purpose | Returns |
|---|---|---|
download.saveAs(path) | Save to a specific path | Promise<void> |
download.suggestedFilename() | Browser-computed filename | string |
download.path() | Temporary file path (GUID name) | Promise<string> |
download.createReadStream() | Read contents without saving | Promise<Readable> |
download.delete() | Delete the temporary file | Promise<void> |
download.failure() | Error message if download failed | Promise<string | null> |
Upload Methods
| Method | Target | Accepts |
|---|---|---|
locator.setInputFiles() | <input type="file"> | Path, paths array, payload, empty array |
fileChooser.setFiles() | File chooser event | Same as setInputFiles() |
fileChooser.isMultiple() | File chooser event | Returns boolean |
fileChooser.element() | File chooser event | Returns ElementHandle |
File Payload Structure
| Property | Type | Purpose |
|---|---|---|
name | string | Filename the app sees |
mimeType | string | MIME type for validation |
buffer | Buffer | File contents in memory |
Decision Guide
| Scenario | Approach |
|---|---|
Visible <input type="file"> | setInputFiles(path) on the locator |
| Hidden input (styled custom control) | setInputFiles(path) on the hidden input |
| Custom button opens native dialog | waitForEvent('filechooser') + setFiles() |
| No file on disk | setInputFiles({ name, mimeType, buffer }) |
| Multiple files | Pass an array to setInputFiles() |
| Clear a selection | setInputFiles([]) |
Best Practices
โ Do This:
// Start the download wait before the click that triggers it
const downloadPromise = page.waitForEvent('download'); // โ
await page.getByRole('button', { name: 'Export' }).click();
// Save downloads explicitly before the context closes
await download.saveAs('./test-results/export.csv'); // โ
// Use a buffer for dynamically generated test content
await input.setInputFiles({ name: 'data.csv', mimeType: 'text/csv', buffer: Buffer.from('a,b') }); // โ
// Register the filechooser wait before clicking the trigger
const chooserPromise = page.waitForEvent('filechooser'); // โ
await page.getByRole('button', { name: 'Upload' }).click();
// Verify the filename matches the server's Content-Disposition
expect(download.suggestedFilename()).toBe('report.pdf'); // โ
// Clear selections by passing an empty array
await input.setInputFiles([]); // โ
โ Don’t Do This:
// Don't await the click before starting the download wait
await page.getByRole('button', { name: 'Export' }).click(); // โ event may fire first
const download = await page.waitForEvent('download');
// Don't assume the downloaded file persists after the test
const path = await download.path(); // โ deleted when context closes
// Don't commit large binary fixtures when a buffer will do
await input.setInputFiles('./fixtures/10mb-video.mp4'); // โ use buffer if content is synthetic
// Don't try to automate the native file dialog
await page.click('input[type="file"]'); // โ opens OS dialog, not automatable
// Don't read `download.path()` expecting the suggested filename
const tempPath = await download.path(); // โ GUID filename, not 'report.csv'
// Don't forget `acceptDownloads` in standalone scripts
const context = await browser.newContext(); // โ downloads disabled by default
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Download event missed | Wait started after the click | waitForEvent before the action |
| Downloaded file disappears | Context closed before saveAs() | Save before the test ends |
path() returns GUID name | Playwright assigns temporary names | Use suggestedFilename() for the real name |
| File chooser never resolves | Wait registered after the dialog opened | Register before clicking the trigger |
| Upload input not found | Input is hidden or styled | Locate the actual input[type="file"] element |
| Multi-file upload only sends one file | Passed a string instead of an array | Use setInputFiles([path1, path2]) |
acceptDownloads not set | Standalone context defaults to false | Pass { acceptDownloads: true } |
Real-World Examples
1. Downloading an invoice and checking its size
const downloadPromise = page.waitForEvent('download');
await page.getByRole('link', { name: 'Invoice #1001' }).click();
const download = await downloadPromise;
await download.saveAs(`./invoices/${download.suggestedFilename()}`);
2. Uploading an avatar from a fixture
await page.getByLabel('Profile photo').setInputFiles('./fixtures/avatar.jpg');
await expect(page.getByRole('img', { name: 'Current avatar' })).toBeVisible();
3. Uploading a CSV generated in memory
await page.getByLabel('Import').setInputFiles({
name: 'users.csv',
mimeType: 'text/csv',
buffer: Buffer.from('email\nalice@example.com'),
});
4. Testing a file type rejection
await page.getByLabel('Upload image').setInputFiles({
name: 'malware.exe',
mimeType: 'application/octet-stream',
buffer: Buffer.from('fake'),
});
await expect(page.getByText('Only JPG and PNG allowed')).toBeVisible();
5. Testing a file size limit
const tooLarge = Buffer.alloc(6 * 1024 * 1024); // 6 MB
await page.getByLabel('Upload').setInputFiles({
name: 'huge.pdf', mimeType: 'application/pdf', buffer: tooLarge,
});
await expect(page.getByText('File must be under 5 MB')).toBeVisible();
6. Re-uploading a downloaded file
const downloadPromise = page.waitForEvent('download');
await page.getByRole('button', { name: 'Export' }).click();
const download = await downloadPromise;
await page.getByLabel('Import').setInputFiles(await download.path());
7. Handling a custom upload button
const chooserPromise = page.waitForEvent('filechooser');
await page.getByRole('button', { name: 'Attach file' }).click();
const chooser = await chooserPromise;
await chooser.setFiles('./fixtures/document.pdf');
8. Uploading multiple files at once
await page.getByLabel('Attachments').setInputFiles([
'./fixtures/photo1.jpg',
'./fixtures/photo2.jpg',
]);
await expect(page.getByText('2 files selected')).toBeVisible();
9. Clearing a file selection
await page.getByLabel('Upload').setInputFiles('./fixtures/file.txt');
await page.getByLabel('Upload').setInputFiles([]);
await expect(page.getByText('No file chosen')).toBeVisible();
10. Verifying download contents as text
const downloadPromise = page.waitForEvent('download');
await page.getByRole('button', { name: 'Download JSON' }).click();
const download = await downloadPromise;
const stream = await download.createReadStream();
const chunks = [];
for await (const chunk of stream) chunks.push(chunk);
const content = JSON.parse(Buffer.concat(chunks).toString());
expect(content.version).toBe('2.0');
Visual
The Download Lifecycle
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ DOWNLOAD EVENT FLOW โ
โ โ
โ Test calls: page.waitForEvent('download') โ
โ โ โ
โ โผ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ Promise pending, listening for event โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ โ
โ โ Test clicks "Export" button โ
โ โผ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ Browser receives attachment response โ โ
โ โ Emits 'download' event โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ โ
โ โผ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ Download object resolves โ โ
โ โ โข suggestedFilename() โ 'report.csv' โ โ
โ โ โข saveAs(path) โ persists to disk โ โ
โ โ โข createReadStream() โ read without saving โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ โ
โ โผ โ
โ Context closes โ temporary file deleted โ
โ Only files saved with saveAs() survive โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Upload Strategy Decision Tree
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ HOW TO UPLOAD A FILE โ
โ โ
โ Does the page have <input type="file">? โ
โ โ โ
โ โโโ YES โโโบ Is the input visible? โ
โ โ โ โ
โ โ โโโ YES โโโบ setInputFiles() โ
โ โ โ โ
โ โ โโโ NO โโโโบ setInputFiles() โ
โ โ (works on hidden) โ
โ โ โ
โ โโโ NO โโโโบ Does a button open a dialog? โ
โ โ โ
โ โโโ YES โโโบ waitForEvent โ
โ ('filechooser') โ
โ + setFiles() โ
โ โ
โ No input at all? Dispatch a drop event with โ
โ DataTransfer (advanced, for drag-drop zones). โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
File Payload Construction
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ IN-MEMORY FILE PAYLOAD โ
โ โ
โ setInputFiles({ โ
โ name: 'data.csv', โโโ filename in UI โ
โ mimeType: 'text/csv', โโโ validation checks โ
โ buffer: Buffer.from( โโโ actual contents โ
โ 'id,name\n1,Alice' โ
โ ) โ
โ }) โ
โ โ
โ No disk write. No fixture file. โ
โ The browser sees a File object โ
โ indistinguishable from a user-selected one. โ
โ โ
โ Use for: โ
โ โข Testing validation (size, type, extension) โ
โ โข Generating unique content per test run โ
โ โข Avoiding binary fixtures in the repository โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| Download event | page.waitForEvent('download') |
| Save a download | download.saveAs(path) |
| Suggested name | download.suggestedFilename() |
| Temporary path | download.path() (GUID name) |
| Upload to input | locator.setInputFiles(path | payload | []) |
| Upload via chooser | page.waitForEvent('filechooser') + setFiles() |
| In-memory file | { name, mimeType, buffer } |
| Clear selection | setInputFiles([]) |
| Multi-file | Array of paths or payloads |
| Context option | acceptDownloads: true (standalone scripts) |
Key takeaways:
- Register the wait before the trigger. Both
downloadandfilechooserevents fire immediately when the action occurs. If the wait is registered after the click, the event is missed and the test hangs. Start the promise, then click. - Downloads are ephemeral until saved. The browser context deletes temporary download files when it closes. Any test that needs the file after the testโor needs to upload it elsewhereโmust call
saveAs()first. suggestedFilename()is the real name. Thepath()method returns a GUID filename assigned by Playwright. UsesuggestedFilename()to assert on or preserve the name the server intended.- Prefer
setInputFiles()over the file chooser. If an<input type="file">exists anywhere in the DOMโeven hiddenโsetInputFiles()works directly. Thefilechooserevent is only necessary when no input is reachable. - Buffers eliminate fixtures. For tests that validate file type, size, or content, constructing a
FilePayloadin memory is faster, more explicit, and avoids committing binary files to the repository. - Empty array clears the selection.
setInputFiles([])resets the input’s FileList, which is the correct way to test a “remove file” button or a reset action. - File size limits are testable with
Buffer.alloc(). An oversized buffer exercises the application’s validation without requiring a real large file on disk.
Remember: File handling in Playwright rests on one principle: the operating system’s file dialog is never automated. Downloads are captured as events and persisted on demand; uploads are performed by assigning files to inputs or file chooser objects. The file system is available to the testโsaveAs() writes, Buffer.from() reads, fs.readFileSync() verifiesโbut the browser does not depend on it to function. A test can download a file, read it, mutate it, and upload it back without ever opening a dialog or committing a fixture. That is the control that makes file workflows testable.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!