I am currently facing an issue while attempting to upload a local file (C:\sample.txt) to my server. I have successfully implemented this using the Chrome web driver, but I am encountering difficulties with the HTMLUnitDriver. Despite trying various methods, I have been unsuccessful in browsing the file item from my local disk.
One approach I tried is through sending keys:
WebElement inputFile = driver.findElement(By.id("file"));
System.out.println(driver.getCurrentUrl());
LocalFileDetector detector = new LocalFileDetector();
String path = "C:\\UploadSample1.txt";
File f = detector.getLocalFile(path);
inputFile.sendKeys(f.getAbsolutePath());
The second method I attempted involves using a Robot:
WebElement browseFile = fluentWait(By.id("browseFile"), driver);
browseFile.click();
File file = new File("C:\\UploadSample1.txt");
driver.switchTo().activeElement();
StringSelection fileNameToWrite = new StringSelection(
file.getAbsolutePath());
Toolkit.getDefaultToolkit().getSystemClipboard()
.setContents(fileNameToWrite, null);
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
In order to save the file to my server, it is crucial that I am able to browse the file item. Simply sending the file path will only search for the file on the server disk. As of now, I am stuck and unable to make progress.
Any assistance or guidance on resolving this issue would be greatly appreciated. Thank you!