Careeroza
File Upload
Upload with sendKeys
<input type="file" id="avatar-upload" accept="image/*">Path photo = Path.of("src/test/resources/files/profile.jpg").toAbsolutePath();
driver.findElement(By.id("avatar-upload")).sendKeys(photo.toString()); // no OS dialog opens
driver.findElement(By.id("save-profile")).click();
System.out.println(wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(".toast"))).getText());Example
Output:
Run ProfilePhotoTest.main()Example output
Profile photo updated
Rules
- Send the absolute path of the file to the
<input type="file">element. Do not click "Browse": Selenium cannot control the operating system's file dialog. - If the input is hidden behind a styled button, it still usually accepts
sendKeys. If not, make it visible with JavaScript first. - Multiple files: join paths with a newline,
sendKeys(path1 + "\n" + path2), when the input hasmultiple. - On Selenium Grid, set
((RemoteWebDriver) driver).setFileDetector(new LocalFileDetector())so the file is sent to the remote machine.
Note: Tools like AutoIT or Robot class were used for upload dialogs in old tutorials. You do not need them with sendKeys.