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 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:
Since these elements accept file paths as input, Selenium can simply send the file path to the element using the method.
✅ Step-by-Step Script in Java
⚙️ Pre-requisites
Make sure you have the following in your Java project:
Selenium WebDriver dependency
Proper browser driver (e.g., ChromeDriver)
🚀 Java Script Example
🛠️ Notes & Best Practices
✅ 1. Always Use Absolute File Paths
requires a full path (e.g., ). 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 .
✅ 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:
Use JavaScript to make it visible:
✅ 4. Use Waits If Necessary
If the file input takes time to render or become clickable:
⚡ 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:
AutoIt (Windows-only)
Robot class (Java)
PyAutoGUI / Sikuli (for complex workflows)
🛠 Java Robot Class (Only if HTML input not available)
🧠 Conclusion
Handling file uploads in Selenium is usually straightforward when the input field is available in the DOM. You can simply use 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.