October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
browser automation

How to Handle File Uploads with Puppeteer

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For a normal HTML file input, locate input[type="file"] and call uploadFile() with the path to the file. If the page opens a chooser only after a button click, start page.waitForFileChooser() before clicking, then accept or cancel the chooser. The path must point to a file in the machine or container where Puppeteer’s Chrome process runs; use absolute paths when connecting to remote Chrome.

Choose the upload method that matches the page

Puppeteer has two practical upload flows. Use direct input assignment when the DOM contains an <input type="file"> that you can select. Use file-chooser handling when the application’s button opens a browser chooser as a user action. These are different browser events, so applying the wrong method commonly produces a timeout or an unchanged form.

Page behavior Puppeteer approach What you control
A file input is present in the DOM ElementHandle.uploadFile() One or more local file paths
A click launches a chooser page.waitForFileChooser(), then fileChooser.accept() or cancel() The chooser response and selected paths

The Puppeteer Files guide summarizes the first method: “For uploading files, you need to locate a file input element and call ElementHandle.uploadFile.” Puppeteer recommends locators for general interaction, but the documented file-upload workflow still uses the lower-level element handle API.

Prerequisites and a reliable test setup

  • Install Puppeteer in your project with npm install puppeteer, or use the browser-management setup appropriate to your existing Puppeteer installation.
  • Make the test file available before launching the browser. Check that it exists and is readable; Puppeteer’s upload APIs do not verify path existence for you.
  • Know where Chrome runs. A relative path is resolved from the Node.js process’s current working directory. With remote Chrome, the file must be available to the environment that performs the upload, and Puppeteer’s documentation requires absolute paths for remote connections.
  • Use a deterministic test file and assert the page’s post-upload result, such as a success message, network response, or displayed filename.

A small precondition check prevents confusing browser errors:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Lexar D40E 128GB Dual USB 3.2 Gen 1 Type-C Jump Drive, Champagne Silver
  • 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 fs from 'node:fs/promises';

const filePath = '/absolute/path/to/fixture.pdf';
await fs.access(filePath);

Upload through a visible file input

Minimal example

Wait for the input, then pass an array of paths to uploadFile. The method sets the input’s selected files; it does not click an operating-system dialog.

import puppeteer from 'puppeteer';

const browser = await puppeteer.launch({headless: true});
const page = await browser.newPage();

await page.goto('https://example.com/upload', {waitUntil: 'networkidle2'});

const fileElement = await page.waitForSelector('input[type="file"]');
await fileElement.uploadFile('/absolute/path/to/photo.jpg');

await page.click('button[type="submit"]');
await page.waitForSelector('.upload-success');

await browser.close();

The documented example also accepts an array, which is required when the input has the multiple attribute:

const fileElement = await page.waitForSelector('input[type="file"]');
await fileElement.uploadFile([
  '/absolute/path/to/first.pdf',
  '/absolute/path/to/second.pdf'
]);

Select the correct input

Pages often contain several file inputs, including hidden inputs for avatars, attachments, and replacement files. Prefer a stable identifier or an accessible relationship to the visible control:

const fileElement = await page.waitForSelector('#avatar-upload');
await fileElement.uploadFile('/absolute/path/to/avatar.png');

If the input is inside an iframe, obtain the frame first and query within it:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const frame = page.frames().find(f => f.url().includes('/profile'));
if (!frame) throw new Error('Profile frame was not found');
const input = await frame.waitForSelector('input[type="file"]');
await input.uploadFile('/absolute/path/to/avatar.png');

Do not use locator.fill() for file selection. The documented locator fill types do not describe selecting local files; use the file-input upload API instead.

Submit and verify

Uploading a file only changes the selected files on the input. The application may upload immediately, require a separate submit button, or wait for a drop-zone event. Follow the site’s actual flow and assert an observable result:

Rank #2
SANDISK 128GB Ultra Flair, USB-A Flash Drive, Up to 150MB/s Read Speeds
  • 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 fileElement.uploadFile('/absolute/path/to/report.pdf');
await page.click('[data-testid="submit-upload"]');

await page.waitForFunction(() => {
  return document.body.textContent?.includes('Upload complete');
});

For applications that upload through XHR or fetch, waiting for the relevant response can be more reliable than a fixed delay:

const responsePromise = page.waitForResponse(response =>
  response.url().includes('/api/uploads') && response.request().method() === 'POST'
);
await page.click('[data-testid="submit-upload"]');
const response = await responsePromise;
if (!response.ok()) throw new Error(`Upload failed with ${response.status()}`);

Handle a page-triggered file chooser

Register the waiter before clicking

When a button launches a chooser, call page.waitForFileChooser() before the click. Puppeteer’s example uses Promise.all so the listener is ready during the click:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import puppeteer from 'puppeteer';

const browser = await puppeteer.launch({headless: true});
const page = await browser.newPage();
await page.goto('https://example.com/upload', {waitUntil: 'networkidle2'});

const [fileChooser] = await Promise.all([
  page.waitForFileChooser(),
  page.click('#upload-file-button')
]);

await fileChooser.accept(['/absolute/path/to/myfile.pdf']);
await page.waitForSelector('.upload-success');
await browser.close();

Calling the waiter after the click is a race: the chooser event may already have fired, leaving the promise waiting until its timeout.

Accept multiple files or cancel

accept() receives a string array, so a multi-file chooser is handled like this:

const [chooser] = await Promise.all([
  page.waitForFileChooser(),
  page.click('#attach-files')
]);
await chooser.accept([
  '/absolute/path/to/a.txt',
  '/absolute/path/to/b.txt'
]);

To dismiss the flow deliberately, call cancel():

const [chooser] = await Promise.all([
  page.waitForFileChooser(),
  page.click('#attach-files')
]);
await chooser.cancel();

A chooser that is neither accepted nor canceled can prevent subsequent chooser dialogs from appearing because the browser allows only one chooser to be open at a time. Always resolve it, including in error-handling paths.

Chooser limitations

Page.waitForFileChooser() must run before the chooser opens and will not return a chooser that is already active. Puppeteer does not support intercepting file dialogs triggered through DOM APIs such as window.showOpenFilePicker. In headful mode, the native picker does not appear to the user when Puppeteer handles it; that is expected, not evidence that the click failed.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
2 Pack 64GB USB Flash Drive USB 2.0 Thumb Drives Jump Drive Fold Storage Memory Stick Swivel Design - Black
  • 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

Paths, containers, and remote Chrome

Resolve paths explicitly

Relative paths use the current working directory, which can change between a local shell, a test runner, and a container. Build an absolute path from the module location or an environment variable:

import path from 'node:path';
import {fileURLToPath} from 'node:url';

const here = path.dirname(fileURLToPath(import.meta.url));
const filePath = path.resolve(here, 'fixtures', 'document.pdf');
await fileElement.uploadFile(filePath);

Remote browser requirement

When your script connects to a Chrome instance running elsewhere, the path is interpreted in the browser-automation environment, not automatically on your laptop. Copy or mount the fixture into that environment and pass its absolute path. A path that exists locally but not in the container will not be made available by Puppeteer.

Permissions and cleanup

  • Ensure the process user can read the file and traverse every parent directory.
  • Avoid placing secrets in fixture files or command-line arguments that your CI system logs.
  • Use temporary files for generated uploads and remove them after the test, while retaining failed-test artifacts when diagnosis requires them.
  • Limit accepted extensions and size in the application as well as in the test; browser automation does not replace server-side validation.

Common failures and fixes

“No node found” or a selector timeout

The selector may be wrong, the input may be inside an iframe, or the page may not have finished rendering. Confirm the frame, wait for the application’s upload UI, and inspect the DOM. If a custom component hides the input, locate the actual input[type="file"] rather than its styled label.

The click works but waitForFileChooser() times out

You may have started the waiter after the click, clicked a control that does not open a chooser, or encountered window.showOpenFilePicker, which Puppeteer cannot intercept through this API. Register the waiter in Promise.all and verify the page’s implementation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The upload completes with an empty or missing file

Check the absolute path inside the running environment, file permissions, and whether the input is replaced by the framework after you selected it. Select the final input immediately before submission and verify the application’s own filename or upload response.

A second chooser never appears

The previous chooser is still unresolved. Call accept() or cancel() in every branch, including a finally block when later steps can throw.

Rank #4
SIMMAX 32GB Memory Stick USB 2.0 Flash Drives Swivel Thumb Drive Pen Drive (32GB Purple)
  • 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.

Headful debugging shows no OS dialog

That is normal when Puppeteer owns the chooser. Debug the page state and chooser promise rather than waiting for a visible native window.

Works locally but fails in CI

CI commonly has a different working directory, container filesystem, user, or browser endpoint. Log the resolved path (without sensitive filenames where inappropriate), run an explicit filesystem access check, and mount fixtures at a known absolute location.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Reliability, timing, and test design

Prefer event-based waits: wait for the input, chooser, upload response, or success state that represents progress. A fixed setTimeout can pass on a fast machine and fail under load. Set timeouts appropriate to the application, but do not hide a selector or network failure with an arbitrarily large value.

Keep browser setup separate from upload assertions. A reusable helper can support both page styles:

export async function uploadViaInput(page, selector, filePaths) {
  const input = await page.waitForSelector(selector);
  await input.uploadFile(filePaths);
}

export async function uploadViaChooser(page, triggerSelector, filePaths) {
  const [chooser] = await Promise.all([
    page.waitForFileChooser(),
    page.click(triggerSelector)
  ]);
  await chooser.accept(filePaths);
}

Run tests with fixtures that cover one file, multiple files, an invalid extension, an oversized file, and a canceled chooser. Those cases exercise both browser mechanics and the application’s validation behavior.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If your goal is to document the page after an upload, or to capture a clean visual result for a test report, ScreenshotNeo can take the screenshot without you managing a Puppeteer browser. It accepts cookie and consent banners as a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each cleanup step can be disabled. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and the response identifies the page verdict and billing status in X-Page-Verdict and X-Billed headers. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use the one-call API after the upload page is publicly reachable:

Best Value
Sale
IMEASON Swivel Design 16GB USB Flash Drive with Keychain, USB 2.0 Portable Thumb Drive Memory Stick, FAT32 Format Flashdrive for Data Storage, Photos, Music, Files (Black, 16 GB)
  • 【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.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo API documentation for capture options such as full-page screenshots, CSS selectors, custom JavaScript, waits, blocked resources, cookies, headers, device presets, PDFs, signed links, asynchronous jobs, and bulk capture.

Python:

import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)

Node.js:

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

ScreenshotNeo’s Free plan includes 1,000 screenshots per month with no card. Paid plans start at $5 for 3,000 shots; every feature is on every plan. Create a free ScreenshotNeo account.

FAQ

Can Puppeteer upload a file without displaying a native dialog?

Yes. Direct input assignment and Puppeteer-managed chooser handling both avoid manual interaction with an operating-system window. A visible native picker is not required.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Does uploadFile() submit the form?

No. It selects files on the input. Submit the form or trigger the application’s upload action and wait for its completion signal separately.

Can I use a relative path?

Yes, when it resolves correctly from the current working directory. Absolute paths are safer, and Puppeteer requires them when connecting to remote Chrome.

What if the site uses drag and drop instead of a file input?

Inspect the implementation. Many drop zones still contain a file input that can be selected directly; if not, the page may require application-specific drag-and-drop event handling beyond the two standard APIs described here.

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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Read next

Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.