Upload a file

Set files on a file input, upload several at once, and clear the selection without touching the OS dialog.

Set files directly on the file input with setInputFiles(). This never opens the operating system file picker, so it runs the same way headless on CI as it does locally.

Set a file on the input

Find the input by its label and pass a path. The path must exist on disk: a missing file throws before the browser is touched.

php
$page->getByLabel('Avatar')->setInputFiles(__DIR__.'/fixtures/avatar.png');

$page->getByRole('button', ['name' => 'Save'])->click();

expect($page->getByText('Avatar updated'))->toBeVisible();

Keep fixtures small and commit them with the test suite. A 20 KB image is easier to reason about than a random file from a temp directory.

Upload several files

Pass an array of paths. The target input must carry the multiple attribute, or the browser keeps only the last file.

php
$page->getByLabel('Attachments')->setInputFiles([
    __DIR__.'/fixtures/report.pdf',
    __DIR__.'/fixtures/data.csv',
]);

Clear the selection

Pass an empty array to remove every file already set on the input.

php
$page->getByLabel('Attachments')->setInputFiles([]);

Expected result

The application should show the uploaded filename, preview, or success message. Assert that visible result after submitting the form; the file input accepting a path only proves the browser selected the file.

Pitfalls

  • Do not automate the OS dialog that opens when a user clicks the upload button. Set the input instead; the dialog has no place in a headless run.
  • Assert the application response, not the input change. A visible success message or a listed filename proves the upload was accepted.

Go next

← All recipes