Use an HTML file input and ElementHandle.uploadFile() to upload files. For a native picker, arm page.waitForFileChooser() before clicking and then accept the file. Downloads need more care: create a browser context with an explicit writable downloadPath, then prove completion with a bounded filesystem or protocol check and an application-level assertion. Puppeteer’s maintained files guide currently says it has no universal programmatic download API, so download configuration alone is not completion detection.
What you need before handling files
- Install a current Puppeteer release (the
puppeteerpackage downloads a compatible Chrome by default) or usepuppeteer-corewhen your team manages the browser binary. - Use absolute paths on the machine running Puppeteer. A path on your laptop is not available to a remote CI worker or container unless you mount or copy it there.
- Give each job its own empty, writable download directory. This prevents an old file or another test from being mistaken for the current result.
API details can change between Puppeteer versions and between Chrome DevTools Protocol and WebDriver BiDi. Check the installed version’s references for file handling, DownloadBehavior, and the Page API.
Upload a file through an HTML input
Basic upload
Most upload controls contain an <input type="file">, even when a styled button hides it. Locate that input and pass one or more absolute paths:
const fileElement = await page.waitForSelector('input[type=file]');
await fileElement.uploadFile('/absolute/path/to/report.pdf');
For a multiple-file input, pass additional paths:
await fileElement.uploadFile(
'/absolute/path/to/report.pdf',
'/absolute/path/to/data.csv'
);
uploadFile changes the browser’s selected files; it does not submit the form or prove that the server received the bytes. Use the application’s submit control and wait for the response, navigation, or a visible success state.
#1 Best Overall
- Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
- Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
- Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
- Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
- 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
Submit and verify the server response
const [response] = await Promise.all([
page.waitForResponse(r => r.url().includes('/upload') && r.ok()),
page.locator('button[type=submit]').click(),
]);
if (!response.ok()) throw new Error(`Upload failed: ${response.status()}`);
await page.locator('[data-testid="upload-success"]').wait();
Use the site’s real endpoint or success selector. A 200 response may still represent an application-level error, so inspect the response body when the API defines a success field.
Handle a button that opens the native file chooser
When JavaScript opens a system picker instead of exposing a usable input, register the chooser wait before the action. Waiting afterward can miss the event.
const [chooser] = await Promise.all([
page.waitForFileChooser({timeout: 5000}),
page.locator('#choose-file').click(),
]);
await chooser.accept(['/absolute/path/to/report.pdf']);
For multiple files, the underlying input must support multiple. Do not rewrite the page’s attributes merely to bypass validation; follow the application’s intended flow and then verify its upload result.
Configure a controlled browser download
Create an isolated context and destination
Set the context download policy and destination when the browser supports it. The destination must be absolute and writable; downloadPath is required with allow or allowAndName.
Windows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallOutdated 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 matchimport puppeteer from 'puppeteer';
import fs from 'node:fs/promises';
const downloadPath = '/absolute/path/to/job-directory';
await fs.mkdir(downloadPath, {recursive: true});
for (const name of await fs.readdir(downloadPath)) {
await fs.rm(`${downloadPath}/${name}`, {force: true});
}
const browser = await puppeteer.launch();
const context = await browser.createBrowserContext({
downloadBehavior: {
policy: 'allow',
downloadPath,
},
});
const page = await context.newPage();
Treat that directory as owned by one job. If you use allowAndName, files are named with a download GUID; the DownloadBehavior reference documents a WebDriver BiDi limitation for that policy. Do not infer a final user-facing filename from a GUID without your own mapping.
Rank #2
- 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
- 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
- Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
- 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
- What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
Trigger the download without a race
Arm the wait for the event that proves the click’s asynchronous result before clicking:
await Promise.all([
page.waitForNavigation({waitUntil: 'domcontentloaded'}),
page.locator('a[data-download]').click(),
]);
If the click does not navigate, wait for the application response instead:
const [downloadResponse] = await Promise.all([
page.waitForResponse(r => r.url().includes('/export') && r.ok()),
page.locator('#export').click(),
]);
A response or navigation confirms the trigger, not necessarily that all bytes have been flushed to disk. Continue with completion checks.
Free tools Windows power users keep installed
One-click scans. No signup required.
Know when the download is finished
Puppeteer’s maintained files guide explicitly states: “Currently, Puppeteer does not offer a way to handle file downloads in a programmatic way.” There is no universal, supported page.on('download') API that replaces your own completion logic. Use one or more of these signals.
Bounded directory polling
Poll a clean job directory until the expected file exists, temporary .crdownload files disappear, and the size remains unchanged for consecutive checks. Always enforce a deadline.
Rank #3
- Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
- Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
- Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
- Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
- What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
import fs from 'node:fs/promises';
async function waitForStableFile(dir, expectedName, {
timeoutMs = 60_000,
intervalMs = 500,
stableChecks = 3,
} = {}) {
const deadline = Date.now() + timeoutMs;
let previousSize = -1;
let stable = 0;
while (Date.now() < deadline) {
const names = await fs.readdir(dir);
if (names.some(n => n.endsWith('.crdownload'))) {
stable = 0;
} else if (names.includes(expectedName)) {
const stat = await fs.stat(`${dir}/${expectedName}`);
if (stat.size > 0 && stat.size === previousSize) stable++;
else stable = 0;
previousSize = stat.size;
if (stable >= stableChecks) return `${dir}/${expectedName}`;
}
await new Promise(resolve => setTimeout(resolve, intervalMs));
}
throw new Error(`Download did not complete within ${timeoutMs} ms`);
}
Stable size is only a heuristic. Validate the expected byte count, checksum, archive contents, or a downstream parser before accepting the artifact. Reject files that pre-date the job or exceed your size limit.
Use protocol or application signals when available
Some Chrome protocol integrations expose download-begun and download-completed notifications. If you use them, still correlate the event with the current job and verify the final path and integrity. An application-generated “export ready” state can be stronger than a generic browser event.
Do these 3 things before closing this tab:
1Scan for outdated or missing drivers - takes under a minute2Clear out junk files and repair common Windows errors3Fix the driver behind crashes, sound loss and screen glitchesWhen a direct HTTP download is safer
If the file URL is stable and your authorization permits it, an HTTP client avoids browser download-policy differences. Preserve only the required origin-scoped cookies or bearer token, check status and content type, stream with a maximum size, and write to the job directory atomically.
const response = await fetch(fileUrl, {
headers: {Authorization: `Bearer ${process.env.DOWNLOAD_TOKEN}`},
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const contentType = response.headers.get('content-type') || '';
if (!contentType.includes('application/pdf')) throw new Error('Unexpected content type');
const bytes = Buffer.from(await response.arrayBuffer());
if (bytes.length === 0 || bytes.length > 100 * 1024 * 1024) throw new Error('Invalid size');
await fs.writeFile('/absolute/path/to/job-directory/report.pdf', bytes);
Keep browser interaction when authentication, navigation, a CSRF token, or a required user gesture is part of the behavior you are testing.
Race-free synchronization patterns
- Put the wait and the action in the same
Promise.all. This applies to file choosers, navigation, and response waits. - Use selectors and URL predicates specific to the operation; a generic network-idle wait can resolve before a queued export starts.
- Give every wait a finite timeout and include the URL, selector, and job identifier in the error.
- Close the page, context, and browser in a
finallyblock, while retaining a failed job directory long enough for diagnosis.
Troubleshooting uploads and downloads
“No element found” or upload does nothing
The control may be inside an iframe, shadow root, or rendered after an interaction. Select the correct frame, wait for the input’s visibility or attachment, and confirm that the path exists and is readable by the Puppeteer process.
Rank #4
- Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
- Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
- Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
- Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
- Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
The chooser timeout expires
The button may not open a native chooser, or the wait was registered after the click. Prefer the actual file input when available; otherwise place waitForFileChooser before the click and verify the selector targets the active control.
Recommended Free Tools
The server says no file was received
Selection alone is not submission. Click the site’s submit button, wait for its upload request, and inspect the response body and success indicator. Check field names and required metadata expected by the server.
The download directory stays empty
Confirm the context—not just another browser context—was created with policy: 'allow' and an absolute writable path. Check that the click was not blocked by a popup, consent screen, authentication redirect, or bot check.
A stale or partial file is accepted
Start with an empty per-job directory, reject .crdownload files, require a bounded deadline, and verify size, checksum, magic bytes, or successful parsing. Never treat a nonzero size by itself as proof of completion.
Works in Chrome but not Firefox or BiDi
Download behavior and notification support differ by browser and protocol. Re-check the version-specific API reference, run a small compatibility test in the target browser, and fall back to an authorized HTTP request where appropriate.
Best Value
- 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
- Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
- Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
- HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
- What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
Performance, reliability, and security
- Reuse a browser process when safe, but isolate cookies, permissions, and download directories per job with separate contexts.
- Stream or impose size limits for large files; avoid holding untrusted multi-gigabyte responses in memory.
- Sanitize server-provided filenames and prevent path traversal. Write to a temporary name, validate it, then rename atomically.
- Keep credentials in environment variables or a secret manager. Do not log cookies, authorization headers, or uploaded file contents.
- Clean up old artifacts according to a retention policy, while preserving failed jobs needed for debugging.
Or skip the browser setup
If your goal is simply a clean image or PDF of a web page rather than testing a browser’s file workflow, ScreenshotNeo provides a single HTTP request. It accepts consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be disabled. Bot checks, 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.
cURL:
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
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}`);
See the complete option list and response details in the ScreenshotNeo documentation. The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots. Sign up for the free plan.
Frequently Asked Questions
Where are Puppeteer downloads saved by default?
Do not rely on an implicit location. Configure a writable absolute downloadPath on the browser context and treat that directory as the job’s destination.
Can I upload a file by setting the input value with JavaScript?
No. Use Puppeteer’s uploadFile on the real file input, or accept the file through a chooser returned by waitForFileChooser; then submit and verify the application result.
Quick wins for a faster PC:
Scan for outdated or missing drivers - takes under a minuteDriver Scan →Repair Windows errors before they cause bigger problemsFix Now →Is a completed download event enough to trust the file?
No. Correlate it with the current job and validate the final filename, size or checksum, and—when possible—the file format or application-level result.
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.

