Selenium · Browser automation foundations
How do you upload a file in Selenium?
Short answer
Send the absolute file path to the file input with sendKeys. For remote Grid runs, set a LocalFileDetector so the client uploads the file to the node before the browser uses it.
A native file input accepts a path directly through sendKeys, which avoids opening the OS file picker. The input does not need to be visible in the layout, but it must be present in the DOM and enabled.
Path file = Paths.get("src/test/resources/fixtures/invoice.pdf").toAbsolutePath();
WebElement input = driver.findElement(By.cssSelector("input[type='file']"));
input.sendKeys(file.toString());
LocalFileDetector detector = new LocalFileDetector();
((RemoteWebDriver) driver).setFileDetector(detector);
input.sendKeys(file.toString());- Use an absolute path; relative paths are resolved against the driver or node process
- Inputs hidden with display none can still accept sendKeys in most browsers
- A LocalFileDetector transfers the file from the client machine to the remote node
- The acceptance criteria usually depend on the input's accept attribute and server validation
- Drag-and-drop upload widgets may need Actions or a hidden input if the app provides one
- Clean up uploaded test files so later runs do not depend on them
Drag-and-drop upload zones often contain a hidden file input for accessibility. Sending the path to that input is much more reliable than trying to automate the OS picker. If there is no input at all, the flow may require a browser-specific or OS-level tool, which is a design smell worth raising.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1Why does uploading fail on a remote Grid without a file detector?
- 2How do you upload to a drag-and-drop zone?
- 3Do you need to make the input visible first?
- 4What should you assert after an upload?
Say it in the interview
I send the absolute path directly to the file input, which bypasses the OS picker. On a remote Grid I set a LocalFileDetector so the client uploads the file to the node first. For drag-and-drop zones I look for a hidden accessible file input, because automating the native picker is unreliable. After upload I wait for the application's confirmation state and clean up the fixture.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Selenium mock interview and get scored feedback on depth, clarity and confidence.