Interview #155: Selenium - Write a script to handle file upload.
Handling file uploads in Selenium WebDriver is a common requirement when automating web applications that include file input elements. Selenium interacts with HTML elements, and for file uploads, the key is to directly set the file path to the <input type="file"> element. This approach works seamlessly because Selenium bypasses the OS-level file chooser popup by interacting with the DOM directly.
Disclaimer: For QA-Testing Jobs, WhatsApp us @ 91-9606623245
🧩 Key Concept
HTML file upload fields look like this:
<input type="file" id="uploadFile">
Since these elements accept file paths as input, Selenium can simply send the file path to the element using the sendKeys() method.
✅ Step-by-Step Script in Java
⚙️ Pre-requisites
Make sure you have the following in your Java project:
🚀 Java Script Example
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class FileUploadExample {
public static void main(String[] args) {
// Set the path to the ChromeDriver executable
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
// Initialize WebDriver
WebDriver driver = new ChromeDriver();
try {
// Navigate to the file upload page
driver.get("https://example.com/upload");
// Maximize window
driver.manage().window().maximize();
// Locate the file input element
WebElement fileInput = driver.findElement(By.id("uploadFile"));
// Provide absolute path to the file on your system
String filePath = "C:\\Users\\YourUser\\Documents\\example.pdf";
// Upload the file by sending the file path
fileInput.sendKeys(filePath);
// Optionally click the Submit or Upload button
WebElement uploadButton = driver.findElement(By.id("submitBtn"));
uploadButton.click();
// Optionally verify upload success
WebElement message = driver.findElement(By.id("uploadMessage"));
System.out.println("Upload message: " + message.getText());
} catch (Exception e) {
e.printStackTrace();
} finally {
// Clean up and close browser
driver.quit();
}
}
}
🛠️ Notes & Best Practices
✅ 1. Always Use Absolute File Paths
sendKeys() requires a full path (e.g., "C:\\Users\\user\\file.txt"). Relative paths might not work as expected.
✅ 2. Do Not Use click() on File Input
You don’t need to click on the file input field or handle any system dialog. Selenium directly interacts with it via sendKeys().
Recommended by LinkedIn
✅ 3. Ensure the File Element is Visible
Some modern apps hide the file input and trigger it using JavaScript. If the input field is hidden:
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].style.display='block';", fileInput);
✅ 4. Use Waits If Necessary
If the file input takes time to render or become clickable:
java
CopyEdit
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); WebElement fileInput = wait.until(ExpectedConditions.elementToBeClickable(By.id("uploadFile")));
⚡ Alternative Approach for Native Dialogs (Non-HTML Uploads)
If the upload is triggered via a native dialog (common in desktop-based file uploaders), you'll need to use tools like:
🛠 Java Robot Class (Only if HTML input not available)
Robot robot = new Robot();
robot.delay(2000);
// Copy file path to clipboard
StringSelection selection = new StringSelection("C:\\path\\to\\file.txt");
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection, null);
// Press Ctrl+V to paste
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
// Press Enter
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
🧠 Conclusion
Handling file uploads in Selenium is usually straightforward when the input field is available in the DOM. You can simply use sendKeys() with the absolute file path to upload files. However, for advanced or non-standard uploaders that use native OS dialogs, additional tools or Java's Robot class may be required. Always prefer HTML-based upload fields for better automation stability.