Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
World desk6 min

How to Upload and Download Files with Selenium in Java

Use Java’s file input and LocalFileDetector for uploads, then configure local or Grid downloads and wait for reliable completion before reading files.

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.

To upload a file with Selenium in Java, locate the page’s input[type=file] element and call sendKeys() with the file’s absolute path. For a remote Selenium Grid session, set a LocalFileDetector first so the file can be transferred to the browser node. Downloads need separate handling: on Grid, a file saved on the remote node is not automatically present on your test machine; use Grid managed downloads to retrieve it.

Upload a file through an HTML file input

Selenium does not operate the operating system’s native file chooser. Instead, send the path directly to the page’s file input, submit the form, and assert a result that shows the upload succeeded. This is Selenium’s documented Java pattern: Selenium file upload documentation.

import java.io.File;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

File uploadFile = new File("src/test/resources/document.pdf");
if (!uploadFile.isFile()) {
    throw new IllegalArgumentException("Upload file not found: " + uploadFile.getAbsolutePath());
}

WebElement fileInput = driver.findElement(By.cssSelector("input[type=file]"));
fileInput.sendKeys(uploadFile.getAbsolutePath());
driver.findElement(By.id("file-submit")).click();

// Replace this locator with an assertion for your application's success state.
String uploadedName = driver.findElement(By.id("uploaded-files")).getText();
if (!uploadedName.contains(uploadFile.getName())) {
    throw new AssertionError("Upload was not confirmed: " + uploadedName);
}

The path must exist in the environment where the test code runs. If the page styles or hides its file control, target the actual input[type=file], not the visible button that opens the native chooser. Adapt the submit locator and confirmation assertion to the application under test.

Upload from Java to a remote Selenium Grid browser

A remote browser cannot ordinarily read a path that exists only on the client machine. Configure LocalFileDetector on the RemoteWebDriver before sending the path; Selenium then transfers the local file for the remote session. See Selenium Remote WebDriver documentation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import java.io.File;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.LocalFileDetector;
import org.openqa.selenium.remote.RemoteWebDriver;

RemoteWebDriver remote = (RemoteWebDriver) driver;
remote.setFileDetector(new LocalFileDetector());

File uploadFile = new File("src/test/resources/document.pdf");
if (!uploadFile.isFile()) {
    throw new IllegalArgumentException("Upload file not found: " + uploadFile.getAbsolutePath());
}
WebElement fileInput = remote.findElement(By.cssSelector("input[type=file]"));
fileInput.sendKeys(uploadFile.getAbsolutePath());
remote.findElement(By.id("file-submit")).click();

Keep the file path local to the test process; the detector handles making it available to the node. If you use a custom WebDriver wrapper or a different Selenium binding version, confirm that the underlying driver is a RemoteWebDriver and that its file detector is configured before sendKeys().

Download with a local browser

For a browser running on the test machine, configure its download directory using that browser driver’s supported preferences or options. The resulting file is written to that directory on the test machine. Do not assume navigation or clicking the download link means the file is fully written: ChromeDriver does not automatically wait for a download to complete, according to its capabilities documentation.

Wait for an application-level completion state when available, or poll the download directory for the expected file and a stable nonzero size before reading it. A fixed sleep can be too short on a slow run and needlessly long on a fast one.

Download and retrieve files from Selenium Grid

With Grid, the browser’s ordinary download directory belongs to the remote node. To retrieve downloads through Selenium’s managed-download feature, enable it on the Grid node or standalone server and request it for the session. Grid documentation lists Chrome, Edge, and Firefox as supported for managed downloads: Grid CLI options and managed-download documentation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. Start the node or standalone Grid with managed downloads enabled, for example: --enable-managed-downloads true.

  2. Create the remote session with the capability se:downloadsEnabled=true.

  3. After the application indicates that the download should be complete, use Selenium’s Java download API to list and retrieve the file.

On Selenium versions exposing HasDownloads, the relevant methods are getDownloadableFiles(), downloadFile(name, targetDirectory), and deleteDownloadableFiles(). The Java remote-driver documentation notes that browser-specific remote features may require Augmenter with a RemoteWebDriver; RemoteWebDriverBuilder augments automatically. Check the API for your installed Selenium version before copying code, because binding interfaces evolve.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
// Assumes `driver` is an augmented driver exposing HasDownloads
// and the session was created with se:downloadsEnabled=true.
import java.nio.file.Path;
import java.time.Duration;
import java.util.Set;
import org.openqa.selenium.HasDownloads;
import org.openqa.selenium.support.ui.FluentWait;

HasDownloads downloads = (HasDownloads) driver;
Path targetDirectory = Path.of("target", "grid-downloads");

Set<String> files = new FluentWait<>(downloads)
    .withTimeout(Duration.ofSeconds(60))
    .pollingEvery(Duration.ofMillis(500))
    .until(d -> {
        Set<String> names = d.getDownloadableFiles();
        return names.contains("report.csv") ? names : null;
    });

downloads.downloadFile("report.csv", targetDirectory);
// Optional cleanup of the session's managed download files:
downloads.deleteDownloadableFiles();

The example waits for the expected name to appear in Grid’s downloadable-file list. That list is only a snapshot; by itself, a listing is not proof that the browser has finished writing the download. Prefer an application completion signal where possible. Grid’s documentation explicitly recommends avoiding hardcoded sleeps and, ideally, giving the application a way to indicate that a file is completely downloaded: Selenium Grid documentation.

Grid also documents a lower-level session files endpoint for listing and retrieving managed downloads. Its retrieval response contains base64-encoded zipped contents that need decoding and unzipping. Prefer the Java HasDownloads interface when available rather than implementing that protocol flow yourself. Managed download files are cleaned up when the session ends or times out.

Choose local downloads or Grid managed downloads

Concern Local browser Remote Selenium Grid
Upload Send the absolute path to input[type=file]. Set Java LocalFileDetector, then send the local absolute path.
Download location The configured browser download directory is on the test machine. The ordinary browser directory is on the remote node; managed transfer is needed to retrieve files through Grid.
Extra setup Configure browser download preferences as needed. Enable --enable-managed-downloads true, request se:downloadsEnabled=true, and use a compatible Selenium Java download API.
Completion checks ChromeDriver does not wait for download completion. The file list is a snapshot; wait for a completion condition before retrieval.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshoot upload and download failures

Or skip the browser setup

If your goal is a screenshot or PDF rather than testing a web form’s upload/download behavior, ScreenshotNeo is a website screenshot API and MCP server. One GET request can return a PNG, JPEG, WebP, or PDF; its clean-shot flow accepts cookie/consent banners like a visitor and removes known consent platforms, newsletter popups, and chat widgets before capture. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and responses identify the page verdict and billing status in headers. AI agents can use its MCP server tools, including take_screenshot, get_page_info, and capture_pdf.

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 setup and options. The Free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000 shots. Sign up for ScreenshotNeo’s free plan.

Frequently Asked Questions

Can Selenium click the computer’s file chooser to upload a file?

No. Send the path to the page’s actual input[type=file] element instead.

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

Can I use the remote Grid file list to tell whether a download is complete?

No. It is a snapshot; wait for a meaningful completion condition before retrieving or checking the file.

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.

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.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair 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.