简体   繁体   中英

File Upload using Selenium HtmlUnitDriver-headless webdriver

I'm trying to upload a local file (C:\\sample.txt) to my server. I have tried to implement this with Chrome web driver and its working absolutely fine. But during implementing the same with HTMLUnitDriver, i couldn't browse the file item from my local disk. I tried the below two methods as well,

1) Send 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());

2) 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);

I need the file item to be browsed, then only i can save it to my server. Because just sending the file path will be searching the file in server disk. Now i'm really stuck and couldn't move further.

Any help is highly appreciated. Thankyou!

If you need to browse to the file first, that isn't possible IMHO; for that you will need AutoIT (as Robot class is not recommended). So your best bet would be sending file path using sendKeys.

formInput.setValueAttribute(formValue); worked fine for me.

Code snippet:

Iterator<String> formValueIterator =  formValues.keySet().iterator();
while(formValueIterator.hasNext()){
    String formKey = formValueIterator.next();
    String formValue = formValues.get(formKey);

    HtmlInput formInput =  form.getInputByName(formKey);

    if (formInput != null)
        if (formInput instanceof HtmlPasswordInput) {
            ((HtmlPasswordInput)formInput).setValueAttribute(formValue);
        } else {
            formInput.setValueAttribute(formValue);
        }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM