Q19 of 37 · Selenium
How do you upload a file with Selenium WebDriver?
Short answer
Short answer: For native `<input type="file">`: send the absolute file path to the input with `.sendKeys(path)` — the browser treats it as a selection. For custom drag-and-drop or hidden inputs, expose the underlying input first or use JS dispatch.
Detail
File upload is one of the few cases where Selenium can't simulate the OS file picker — and doesn't need to. The W3C WebDriver spec lets you bypass the picker by writing a path directly to a file input.
Native input:
WebElement fileInput = driver.findElement(By.cssSelector("input[type=file]"));
fileInput.sendKeys("/absolute/path/to/file.csv");
The browser treats this as a user selection and fires the same events as a real picker. The path must be absolute and the file must exist on the machine running the browser (which matters for Grid).
Hidden file inputs: many designs hide the <input type=file> behind a styled "Upload" button. The input still exists in the DOM — find it directly (don't click the button) and sendKeys to it:
// The visible button is decorative; sendKeys to the hidden input
WebElement input = driver.findElement(By.cssSelector("input[type=file]"));
((JavascriptExecutor) driver).executeScript(
"arguments[0].style.display = 'block';", input
);
input.sendKeys(absolutePath);
Drag-and-drop uploaders: HTML5 dnd is hard to fake from Selenium. The pragmatic approach is the same — find the underlying input and use sendKeys. If there isn't one (genuine JS-only dnd handler), fall back to a JS-dispatched DataTransfer event, but this is rare in practice.
Selenium Grid / remote drivers: the file path is relative to the node, not your test runner. Use driver.setFileDetector(new LocalFileDetector()) so Selenium uploads the file to the node before sendKeys runs.
// EXAMPLE
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.LocalFileDetector;
import org.openqa.selenium.remote.RemoteWebDriver;
public void uploadCsv(RemoteWebDriver driver, String absolutePath) {
// Required when running against Selenium Grid
driver.setFileDetector(new LocalFileDetector());
WebElement input = driver.findElement(By.cssSelector("input[type=file]"));
input.sendKeys(absolutePath);
driver.findElement(By.cssSelector("[data-test=upload-submit]")).click();
}