| | |

Playwright 18 ๐ŸŽญ File Downloads and Uploads โ€” Handling file system interactions

โฑ๏ธ Estimated read: 15 min | |

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

MethodPurposeReturns
download.saveAs(path)Save to a specific pathPromise<void>
download.suggestedFilename()Browser-computed filenamestring
download.path()Temporary file path (GUID name)Promise<string>
download.createReadStream()Read contents without savingPromise<Readable>
download.delete()Delete the temporary filePromise<void>
download.failure()Error message if download failedPromise<string | null>

Upload Methods

MethodTargetAccepts
locator.setInputFiles()<input type="file">Path, paths array, payload, empty array
fileChooser.setFiles()File chooser eventSame as setInputFiles()
fileChooser.isMultiple()File chooser eventReturns boolean
fileChooser.element()File chooser eventReturns ElementHandle

File Payload Structure

PropertyTypePurpose
namestringFilename the app sees
mimeTypestringMIME type for validation
bufferBufferFile contents in memory

Decision Guide

ScenarioApproach
Visible <input type="file">setInputFiles(path) on the locator
Hidden input (styled custom control)setInputFiles(path) on the hidden input
Custom button opens native dialogwaitForEvent('filechooser') + setFiles()
No file on disksetInputFiles({ name, mimeType, buffer })
Multiple filesPass an array to setInputFiles()
Clear a selectionsetInputFiles([])

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

PitfallWhy It HappensFix
Download event missedWait started after the clickwaitForEvent before the action
Downloaded file disappearsContext closed before saveAs()Save before the test ends
path() returns GUID namePlaywright assigns temporary namesUse suggestedFilename() for the real name
File chooser never resolvesWait registered after the dialog openedRegister before clicking the trigger
Upload input not foundInput is hidden or styledLocate the actual input[type="file"] element
Multi-file upload only sends one filePassed a string instead of an arrayUse setInputFiles([path1, path2])
acceptDownloads not setStandalone context defaults to falsePass { 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

ItemValue
Download eventpage.waitForEvent('download')
Save a downloaddownload.saveAs(path)
Suggested namedownload.suggestedFilename()
Temporary pathdownload.path() (GUID name)
Upload to inputlocator.setInputFiles(path | payload | [])
Upload via chooserpage.waitForEvent('filechooser') + setFiles()
In-memory file{ name, mimeType, buffer }
Clear selectionsetInputFiles([])
Multi-fileArray of paths or payloads
Context optionacceptDownloads: true (standalone scripts)

Key takeaways:

  • Register the wait before the trigger. Both download and filechooser events 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. The path() method returns a GUID filename assigned by Playwright. Use suggestedFilename() 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. The filechooser event is only necessary when no input is reachable.
  • Buffers eliminate fixtures. For tests that validate file type, size, or content, constructing a FilePayload in 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.

Was this helpful?


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!