File upload and download in Playwright

7 min read · TypeScript · 3 linked exercises

File dialogs belong to the operating system, not to the page, so a test can't click through them. Playwright doesn't try. It sets the files on the input directly, and it hands you each download as an object you can read.

This guide covers both directions: plain inputs, files created in the test, custom upload buttons and drop zones, then catching a download and checking what's inside it.

Upload with setInputFiles()

Find the file input, usually by its label, and give it a path. No dialog opens.

const input = page.getByLabel('Choose file');

await input.setInputFiles('tests/files/report.txt');
await expect(page.getByTestId('uploaded-file')).toHaveText('Selected file: report.txt');

// Several files, for an input with the multiple attribute
await input.setInputFiles(['a.txt', 'b.txt']);

// Clear the selection
await input.setInputFiles([]);

A relative path is resolved from the folder you run the tests in, usually the project root. Keep test files in the repository, or create them as shown next.

Practise it
  • File UploadIntermediateUpload a file from disk, then clear the selection.

Create the file in the test

Most upload tests don't care what the file contains, only about its name, type and size. Pass those instead of a path and nothing has to exist on disk:

await page.getByLabel('Profile photo').setInputFiles({
  name: 'avatar.png',
  mimeType: 'image/png',
  buffer: Buffer.alloc(20 * 1024), // 20 KB of zeros
});

This makes validation rules easy to test. A file over the limit is one line, with no large file in the repository:

await page.getByLabel('Profile photo').setInputFiles({
  name: 'huge.png',
  mimeType: 'image/png',
  buffer: Buffer.alloc(2 * 1024 * 1024),
});

await expect(page.getByRole('alert')).toHaveText('huge.png is 2.0 MB. The limit is 1 MB.');

The input's accept attribute only filters the system dialog. setInputFiles() skips the dialog, so it can send a GIF to an input that accepts PNG. That's useful: it tests whether the app checks the type itself.

When the test does need a real file, write it to the test's own output folder with testInfo.outputPath('report.txt'). Parallel tests then never write to the same file.

Practise it
  • File UploadIntermediateSend an image, a wrong type and a file over the size limit.

Custom buttons and hidden inputs

Many pages hide the real input and show a styled "Add files" button. To test the button the user clicks, wait for the file chooser it opens:

const chooserPromise = page.waitForEvent('filechooser');
await page.getByRole('button', { name: 'Add files' }).click();
const chooser = await chooserPromise;

expect(chooser.isMultiple()).toBe(true);
await chooser.setFiles(['a.txt', 'b.txt']);

Start waiting before the click, as with every event in Playwright. If you start waiting after it, the event may already have fired, and the wait times out.

The shortcut is to fill the hidden input directly. setInputFiles() doesn't need the input to be visible:

await page.locator('input[type="file"][multiple]').setInputFiles(files);

The shortcut is fine for tests about what happens after the upload. Keep one test that goes through the button, so you know the button still works.

Drop zones

A drop zone reads files from the drop event. Playwright can't drag a file in from the desktop, but it can build the same event in the page and dispatch it:

const dataTransfer = await page.evaluateHandle(() => {
  const transfer = new DataTransfer();
  transfer.items.add(new File(['hello'], 'c.txt', { type: 'text/plain' }));
  return transfer;
});

await page.getByText('Drop files here').dispatchEvent('drop', { dataTransfer });

Check first whether the drop zone also has a file input. Many do, so that the upload works from the keyboard, and setInputFiles() on it is simpler than building an event.

Check that the upload arrived

A file name appearing on the page proves the browser selected the file. It doesn't prove the server received it. Wait for the upload request and read its response:

const responsePromise = page.waitForResponse('**/api/upload');
await page.getByRole('button', { name: 'Upload', exact: true }).click();
const response = await responsePromise;

expect(await response.json()).toMatchObject({
  files: [{ name: 'a.txt', size: 4 }],
  totalBytes: 4,
});

Test the failure as well. Servers have their own size limit, often different from the one in the page, and the app should show the server's error to the user.

Practise it
  • File UploadIntermediateAdd files by button and by drop, upload them and check the response.

Catch a download

A download is an event on the page. Start waiting, click, then use the Download object:

const downloadPromise = page.waitForEvent('download');
await page.getByRole('button', { name: 'Export users as CSV' }).click();
const download = await downloadPromise;

expect(download.suggestedFilename()).toBe('users.csv');

suggestedFilename() is the name the browser would save the file under. It comes from the link's download attribute or from the server's Content-Disposition header.

Playwright stores the file in a temporary folder and deletes it when the browser context closes, which is the end of the test. download.path() gives you that temporary path. download.saveAs() copies the file somewhere it will stay:

const saved = testInfo.outputPath(download.suggestedFilename());
await download.saveAs(saved);
Practise it
  • File DownloadIntermediateCatch four downloads: two exports, a static file and a server-named report.

Check what's inside

The file name is only half of the test. An export with the right name and the wrong rows is still a bug. Read the file with Node and assert on its contents:

import { readFile } from 'node:fs/promises';

const content = await readFile(await download.path(), 'utf-8');
const lines = content.trim().split('\n');

expect(lines[0]).toBe('firstName,lastName,role');
expect(lines).toHaveLength(5); // the header and four users
expect(lines).toContain('Anna,Kowalski,User');

JSON is easier still:

const users = JSON.parse(await readFile(await download.path(), 'utf-8'));

expect(users).toHaveLength(6); // exported with inactive users included
expect(users).toContainEqual({ firstName: 'Lena', lastName: 'Fischer', role: 'Manager' });

Names that contain a date or an id change from run to run. Match their shape with a regular expression:

expect(download.suggestedFilename()).toMatch(/^report-\d{4}-\d{2}\.txt$/);

PDF and spreadsheet files need a library to parse. Decide what the test must prove. Often the name, a non-zero size and one value read through the app's API are enough.

Practise it
  • File DownloadIntermediateCheck the rows of a CSV export and the objects in a JSON export.
  • UI + API TogetherAdvancedDownload an invoice and compare its total with the order from the API.

Pitfalls

  • Waiting after the click. Create the download or filechooser promise first. A fast page fires the event before a later line starts listening.
  • Reading the file after the test. The temporary file is gone once the context closes. Use saveAs() to keep it.
  • Shared file names. Two parallel tests that write export.csv to the same folder overwrite each other. Use testInfo.outputPath().
  • Trusting the page alone. Assert what the server received and what the file contains, not only the message on the screen.

Exercises in this guide

More guides