File upload
BeginnerA file input with a 1 MB limit and a list of allowed types, with success and error messages.
Practice area
The file never leaves your browser; it is only inspected here.
Tasks to automate
- Upload a small PNG and assert the file name and size are shown.
- Upload a .exe or .txt file and assert the type error.
- Upload a file larger than 1 MB and assert the size error.
- Clear the selection and assert the info line is empty again.
Model solutions
Try the tasks first. These show one good way, not the only way.
Selenium (Java)
// Send the absolute path straight to the input. Do not click the button or drive the OS dialog.
driver.findElement(By.id("pg-file"))
.sendKeys(Path.of("src/test/resources/photo.png").toAbsolutePath().toString());
String info = driver.findElement(By.id("pg-file-info")).getText();
assertTrue(info.contains("photo.png"));
Playwright (TypeScript)
await page.locator('#pg-file').setInputFiles('tests/fixtures/photo.png');
await expect(page.locator('#pg-file-info')).toContainText('photo.png');
// Without a file on disk
await page.locator('#pg-file').setInputFiles({ name: 'notes.txt', mimeType: 'text/plain', buffer: Buffer.from('hi') });
await expect(page.locator('#pg-file-error')).toBeVisible();
Element IDs on this page are stable and will not change. Nothing you do here is sent to a server.
