Free tools Windows power users keep installed
One-click scans. No signup required.
The usual fix is to target the real <input type="file">, pass a path or payload in the documented shape, and resolve relative paths from the test process’s current working directory. A styled “Upload” button is often only a trigger. If the page creates the input dynamically, register a file-chooser wait before clicking and then call setFiles(). Finally, verify that the application processed the assigned file; Playwright assigning files and your app uploading them are separate steps.
What setInputFiles actually targets
Playwright’s upload API operates on an HTML file input. The official documentation says the first argument must point to an input element whose type is file (Microsoft Playwright input guide, accessed September 29, 2026). A visible button, drop zone, label, or framework component is not necessarily that element.
Start by inspecting the rendered DOM. You should find something like:
<label for="resume">Upload resume</label>
<input id="resume" type="file" accept=".pdf">
Prefer a semantic locator when the label is correctly associated:
#1 Best Overall
- USB-C 2-in-1 storage OTG: The Lexar JumpDrive Dual Drive D40E features USB Type-A and Type-C connectors in a slim, portable form factor for easy device compatibility
- Transfer speeds up to 100MB/s: Based on internal testing, performance may vary depending upon the host device, interface, and usage conditions. 1MB=1,000,000 bytes
- Plug and Play: Widely compatible with USB Type-C smartphones, tablets, laptops, Macs, and traditional Type-A devices, no software installation required. The 360° swivel design allows for easy switching between connectors without the hassle of losing a cap
- Durable & Compact: The Lexar D40E USB memory stick features a metal enclosure, withstands temperatures from 0° to 50° C (32°F to 122°F), and is lightweight at 26g with dimensions of 70.4 x 16.9 x 11.7mm
- Security & Warranty: Securely protects files using an advanced security software solution with 256-bit AES encryption. Backed by a Lexar 3-year limited warranty
import path from 'node:path';
const filePath = path.resolve(process.cwd(), 'fixtures/resume.pdf');
await page.getByLabel('Upload resume').setInputFiles(filePath);
If the label association is broken, target the input directly and make the selector specific:
await page.locator('input[type="file"][name="resume"]').setInputFiles(filePath);
The selector-based Page API also expects a selector for an input element and can use an input associated with a label (Playwright Page API reference).
Use the correct argument form
The Locator API accepts a single path, an array of paths, one directory for a webkitdirectory input, an in-memory file object, or an empty array to clear the selection (Playwright Locator API reference). Match the value to the input’s behavior.
| Need | JavaScript/TypeScript | Why |
|---|---|---|
| One file | setInputFiles('/absolute/path/report.pdf') |
Assigns one file to a normal file input. |
| Several files | setInputFiles(['/tmp/a.txt', '/tmp/b.txt']) |
Uses the documented array form; the input must allow multiple files. |
| Generated content | setInputFiles({ name: 'report.txt', mimeType: 'text/plain', buffer: Buffer.from('test content') }) |
Avoids a dependency on a fixture file on disk. |
| Directory upload | setInputFiles('/absolute/path/photos') |
Pass one directory to an input using webkitdirectory. |
| Clear selection | setInputFiles([]) |
Removes the files currently assigned to the input. |
For an in-memory payload, include a file name, MIME type, and byte buffer:
Do these 3 things before closing this tab:
1Clear out junk files and repair common Windows errors2Scan for outdated or missing drivers - takes under a minute3Repair Windows errors before they cause bigger problemsRank #2
- High-speed USB 3.0 performance of up to 150MB/s(1) [(1) Write to drive up to 15x faster than standard USB 2.0 drives (4MB/s); varies by drive capacity. Up to 150MB/s read speed. USB 3.0 port required. Based on internal testing; performance may be lower depending on host device, usage conditions, and other factors; 1MB=1,000,000 bytes]
- Transfer a full-length movie in less than 30 seconds(2) [(2) Based on 1.2GB MPEG-4 video transfer with USB 3.0 host device. Results may vary based on host device, file attributes and other factors]
- Transfer to drive up to 15 times faster than standard USB 2.0 drives(1)
- Sleek, durable metal casing
- Easy-to-use password protection for your private files(3) [(3)Password protection uses 128-bit AES encryption and is supported by Windows 7, Windows 8, Windows 10, and Mac OS X v10.9 plus; Software download required for Mac, visit the SanDisk SecureAccess support page]
await page.getByLabel('Upload report').setInputFiles({
name: 'report.txt',
mimeType: 'text/plain',
buffer: Buffer.from('test content'),
});
Do not pass a plain string containing file contents when an object is required, and do not pass multiple paths to an input that does not support multiple selection.
Fix relative-path failures
Relative paths are resolved from the process’s current working directory, not from the directory containing the test file (Locator API reference). A fixture at tests/fixtures/report.pdf can therefore be missed when a package script, monorepo task, or CI job starts in a different directory.
Make the runtime location visible and resolve an absolute path:
import fs from 'node:fs';
import path from 'node:path';
console.log('working directory:', process.cwd());
const filePath = path.resolve(process.cwd(), 'tests/fixtures/report.pdf');
if (!fs.existsSync(filePath)) {
throw new Error(`Fixture is missing: ${filePath}`);
}
await page.locator('input[type="file"]').setInputFiles(filePath);
In a test module that should be independent of the launch directory, derive the fixture from the module location instead:
Rank #3
- What You Get - 2 pack 64GB genuine USB 2.0 flash drives, 12-month warranty and lifetime friendly customer service
- Great for All Ages and Purposes – the thumb drives are suitable for storing digital data for school, business or daily usage. Apply to data storage of music, photos, movies and other files
- Easy to Use - Plug and play USB memory stick, no need to install any software. Support Windows 7 / 8 / 10 / Vista / XP / Unix / 2000 / ME / NT Linux and Mac OS, compatible with USB 2.0 and 1.1 ports
- Convenient Design - 360°metal swivel cap with matt surface and ring designed zip drive can protect USB connector, avoid to leave your fingerprint and easily attach to your key chain to avoid from losing and for easy carrying
- Brand Yourself - Brand the flash drive with your company's name and provide company's overview, policies, etc. to the newly joined employees or your customers
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const here = path.dirname(fileURLToPath(import.meta.url));
const filePath = path.join(here, 'fixtures', 'report.pdf');
if (!fs.existsSync(filePath)) throw new Error(`Not readable: ${filePath}`);
await page.getByLabel('Upload report').setInputFiles(filePath);
The same rule applies in containers and CI: the file must exist inside the environment where the Playwright process runs, with permissions that allow that process to read it. A path that exists on your laptop is not automatically present in a remote worker.
Complete TypeScript examples
Stable input already in the DOM
import { test, expect } from '@playwright/test';
import path from 'node:path';
test('uploads a report', async ({ page }) => {
await page.goto('https://example.test/upload');
const input = page.getByLabel('Upload report');
await expect(input).toHaveCount(1);
await input.setInputFiles(path.resolve(process.cwd(), 'fixtures/report.pdf'));
// Verify the application reacted, not only that Playwright assigned the file.
await expect(page.getByText('report.pdf')).toBeVisible();
await expect(page.getByRole('button', { name: 'Submit' })).toBeEnabled();
});
Multiple files
await page.getByLabel('Upload files').setInputFiles([
path.resolve(process.cwd(), 'fixtures/a.txt'),
path.resolve(process.cwd(), 'fixtures/b.txt'),
]);
Generated file without a fixture
await page.locator('input[type="file"]').setInputFiles({
name: 'generated.csv',
mimeType: 'text/csv',
buffer: Buffer.from('id,namen1,Adan'),
});
Handle a dynamically created file chooser
Some applications do not render the file input until a button is clicked. In that case, calling setInputFiles on a locator found before the click can fail because there is no matching input. Wait for the chooser before clicking; otherwise the event can be missed.
const fileChooserPromise = page.waitForEvent('filechooser');
await page.getByRole('button', { name: 'Upload file' }).click();
const fileChooser = await fileChooserPromise;
await fileChooser.setFiles(filePath);
Playwright documents the filechooser event as being emitted when a chooser is supposed to appear, such as after clicking an <input type=file> trigger (Page API reference). The important ordering is: create the wait, click the trigger, obtain the chooser, then call setFiles.
If the click and chooser must be synchronized as one operation, use a promise pair:
PC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11Outdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchRank #4
- GOOD VALUE PACKAGE - 1 Pack 32GB Memory Stick USB 2.0 Flash Drives with great cost performance and high quality.
- BIG CAPACITY - The available capacity: 29.10GB-29.8GB, You can save the data of movies, music, photos, designs, programs, manuals, handouts in a high speed.Good performance in digital data storing, transferring and sharing with families, friends, workmates, clients and machines.
- EASY TO USE & PLUG AND WORK - Support windows 7 / 8 / 10 / Vista / XP / 2000 / ME / NT Linux and Mac OS, Compatible with USB2.0 and below.
- TWISTTURN DESIGN & EASY CARRY - The metal clip rotates 360° round the ABS plastic body which with rubber oil skin feeling finish. The capless design can avoid lossing of cap, and providing efficient protection to the USB port.
- WARRANTY & SUPPORT - SIMMAX logo is laser printed on the USB connector surface, our products are of good quality and we promise that any problem about the product within one year since you buy.
const [chooser] = await Promise.all([
page.waitForEvent('filechooser'),
page.getByRole('button', { name: 'Upload file' }).click(),
]);
await chooser.setFiles(filePath);
Python equivalents
Locator upload
from pathlib import Path
from playwright.async_api import async_playwright
async def upload(page):
file_path = Path.cwd() / "fixtures" / "report.pdf"
if not file_path.is_file():
raise FileNotFoundError(file_path)
await page.get_by_label("Upload report").set_input_files(str(file_path))
Several files, bytes, and clearing
await page.get_by_label("Upload files").set_input_files([
"fixtures/a.txt",
"fixtures/b.txt",
])
await page.get_by_label("Upload report").set_input_files(
files=[{
"name": "report.txt",
"mimeType": "text/plain",
"buffer": b"test content",
}]
)
await page.get_by_label("Upload report").set_input_files([])
The Python guide documents path, multiple-file, directory, clearing, and byte-buffer forms (Playwright input guide).
Dynamic chooser
async with page.expect_file_chooser() as fc_info:
await page.get_by_role("button", name="Upload file").click()
file_chooser = await fc_info.value
await file_chooser.set_files("/absolute/path/report.pdf")
Separate assignment from application processing
A successful setInputFiles call only means Playwright assigned files to the input. Your application may wait for a change event, validate type or size, generate a preview, or send an HTTP request afterward. Test the application’s observable result with one of these checks:
- Wait for a preview or file name to become visible.
- Wait for a status such as “Uploaded” or an enabled submit button.
- Wait for the upload request and assert its response.
- Check that an error message appears for an intentionally invalid file.
const uploadResponse = page.waitForResponse(response =>
response.url().includes('/api/upload') && response.request().method() === 'POST'
);
await page.locator('input[type="file"]').setInputFiles(filePath);
await expect((await uploadResponse).ok()).toBeTruthy();
If the page requires an explicit submit or an additional “Start upload” click, perform that action after assigning the file. Do not treat a populated input as proof that the server accepted the upload.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Diagnostic checklist for timeouts and no-op uploads
- Inspect the element: confirm the matched node is
<input type="file">, not a button or wrapper. - Check cardinality: use
await locator.count()and require one match. A generic selector may match hidden inputs for several components. - Use a specific locator: prefer an associated label, a unique name, role context, or test id.
- Confirm the file: log the absolute path, check that it exists, and ensure the CI/container can read it.
- Match the shape: use an array for multiple files, one directory for
webkitdirectory, and an object for generated bytes. - Synchronize dynamic controls: create
waitForEvent('filechooser')orexpect_file_chooser()before the click. - Check the timeout: locator actions use a configurable timeout; the Locator API documents that a zero value disables the timeout. Increase it only after fixing locator and path problems.
- Check application state: wait for the app’s request, preview, status, or validation result after assignment.
A timeout usually means Playwright could not resolve or act on the intended locator within the configured period. It does not by itself prove that the server rejected the file. A historical issue reported a file not uploading through setInputFiles; use such reports as version-specific context and rely on the current API behavior (Playwright issue tracker).
Recommended Free Tools
Best Value
- 【16GB Flash Drive】USB flash drives with 16GB capacity, meet your needs of daily use on work, school, home and travelling for photos, music, videos, files storage and transfer. IMEASON thumb drives can be used to store different files, easy to data backup.
- 【Metal Swivel Cap Design】USB thumb drive is metal swivel cover provides extra protection for the usb thumbdrive connector, no usb drive cap to lose; keychain design makes it easier to carry without worrying lose it.
- 【Wide Compatibility】USB drive supports Windows 7/8/10/11 / Vista / XP / Unix / 2000 / ME / NT Linux and Mac OS, also Supports USB 2.0 and 1.1 ports. USB Stick support TV, desktop, notebook computer, car, audio and other device. The USB Memory Stick is your great data storage and transfer companion with traveling and working.
- 【Easy to use】usb memory stick is plug and play without any software installation. Just simply plug the Flashdrive into the port of your USB-compatible devices such as computer, laptop to start data storage or transmission.
- 【What You Get】16 GB USB Flash Drive Thumb Drive, The default format of the usb storage flash drive is FAT32.
Choosing the right fix
| Situation | Preferred method | Reason |
|---|---|---|
| Stable visible file input | locator.setInputFiles(path) |
Direct and deterministic. |
| Multiple files | locator.setInputFiles([paths]) |
Uses the documented array form. |
| Generated content | Payload with name, MIME type, and buffer | No fixture or filesystem dependency. |
| Input appears after a click | Wait for chooser, then setFiles |
Synchronizes with the dynamic control. |
| Remove current selection | setInputFiles([]) |
Uses documented clearing behavior. |
Or skip the browser setup
If your goal is a rendered image or PDF rather than testing an upload flow, ScreenshotNeo provides a website screenshot API and MCP server. It accepts a URL and returns PNG, JPEG, WebP, or PDF; it is not a replacement for Playwright upload assertions, but it avoids maintaining browser-capture code for screenshots.
One request is enough (see the ScreenshotNeo documentation):
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://screenshotneo.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://screenshotneo.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://screenshotneo.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
Before capture, ScreenshotNeo can accept cookie or consent banners and remove more than 60 known consent platforms, newsletter popups, and chat widgets; each step can be disabled. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing status. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients. The Free plan includes 1,000 shots per month without a card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.
FAQ
Frequently Asked Questions
Can setInputFiles upload a file to a custom drag-and-drop widget?
Only if the widget ultimately exposes a file input or a file chooser that Playwright can control. Otherwise test the widget through its supported browser interaction and verify the resulting application request.
Quick wins for a faster PC:
Clear out junk files and repair common Windows errorsFree Scan →Scan for outdated or missing drivers - takes under a minuteDriver Scan →Why does the input exist in the source but not in the test?
The input may be rendered only after hydration, a route change, or a button click. Wait for the relevant state, or use the file-chooser event sequence for a dynamically created control.
Should I test the browser assignment and the server upload separately?
Yes. Assert the file input or preview after assignment, then separately assert the upload request or application status so a client-side and server-side failure are distinguishable.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

