How to automate file upload in Selenium Webdriver

asked 3 months ago

Upload: Uploading files in Selenium WebDriver is done using the sendKeys() method on an HTML input element with type="file". By sending the full path of the file as a string, the file is uploaded automatically.

Navigate to https://www.qafeast.com/demo,click the upload and download tab.

Press F12 in the keyboard and inspect Choose File button

 

 

Using send keys:

WebElement uploadFile = driver.findElement(By.id("file-upload"));
// change the path of the file
uploadFile.sendKeys("D:\\user\\sample\\simple test.txt");
driver.findElement(By.id("file-submit")).click();// click the "UploadFile" button


Keyboard event using robot keys:

If the type attribute is not set to "file" in the HTML input element, then file uploading cannot be performed using the sendKeys() method. In such cases, Selenium can still click the "Choose File" button to open the native file upload dialog, but Selenium WebDriver cannot interact with OS-level pop-up windows.

To handle this scenario, keyboard events can be simulated using Java's Robot class. This approach copies the file path to the clipboard, pastes it into the dialog using Ctrl + V, and then presses Enter to confirm the upload.
However, this method works only when the file dialog is visible and in focus. If the dialog or input is hidden or off-screen, the simulation may fail.

Once the file dialog is open, simulate the keyboard events as shown below:

StringSelection strSel = new StringSelection("C:\\SeleniumResume.doc"); // Store the file path in clipboard
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(strSel, null);

Robot robot = new Robot(); // Create a Robot class object

robot.keyPress(KeyEvent.VK_CONTROL); // Press and hold Ctrl
robot.keyPress(KeyEvent.VK_V);       // Press V
robot.keyRelease(KeyEvent.VK_V);     // Release V
robot.keyRelease(KeyEvent.VK_CONTROL); // Release Ctrl

Thread.sleep(3000); // Optional delay for reliability

robot.keyPress(KeyEvent.VK_ENTER);   // Press Enter to confirm file selection
robot.keyRelease(KeyEvent.VK_ENTER); // Release Enter