Using HtmlUnitDriver-headless webdriver to achieve File Upload via Selenium

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!

Answer №1

In my opinion, browsing to the file directly is not feasible without AutoIT as Robot class is not advisable for this task. Sending the file path using sendKeys would be your optimal solution.

Answer №2

Using formInput.setValueAttribute(formValue); was the perfect solution in my case.</p>

<p>Here is the code snippet I utilized:</p>

<pre><code>The process starts by creating an iterator for the form values and iterating through them to set the corresponding input attributes:

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

    HtmlInput formInput =  form.getInputByName(formKey);

    If the formInput exists, it checks if it's a password field or not, setting the value attribute accordingly:

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

}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

trigger a function by selecting a dynamically added hyperlink

I am currently working on an MVC view that contains a link in jQuery. When this link is clicked, it triggers a JavaScript function. I am facing some challenges in calling the function and passing parameters to it. Here is the link: var cell5 = $( ...

Searching for ever-changing information

I am currently facing an issue with my code: entryData = new Entry[] { new Entry( path1, name1, tag1 ), new Entry( path2, name2, tag2 ), new Entry( path3, name3, tag3 ), new Entry( path4, name4, tag4 ) }; The above data p ...

Angular Typescript consistently returns false when comparing arrays

I've been working on comparing two nested arrays, but it keeps returning false. The goal is to compare the saleLineList in each saleBlock from this.saleBlockList with the saleLineList in each saleBlock from saleBlockList. Even after modifying the da ...

Ways to restrict input text to a specific set of values

When using an input text form, I need to ensure that users only insert values ranging from 1 to 10. However, my attempts to utilize a mask for customization have resulted in allowing values higher than 10. How can I restrict the input to only be allowed b ...

Discover the most helpful keyboard shortcuts for Next.js 13!

If you're working with a standard Next.js 13 app that doesn't have the experimental app directory, setting up keyboard shortcuts can be done like this: import { useCallback, useEffect } from 'react'; export default function App() { c ...

What is the best way to create a text input that is both secure and non-editable?

While I am aware of the <input type="text" readonly /> possibility, it is not entirely secure. For example, if there is an input field that must remain uneditable by users, making it "readonly" can still be bypassed by inspecting the code and remov ...

The error message "trying to access markers property of undefined in the render function" occurred

I encountered this error while running my react-native component and need assistance. An error stating "undefined is not an object (evaluating 'this.state.markers.map')" occurred. This error appears in the following locations: c:\proje ...

What is the best way to retrieve JSON data values for buttons that have been clicked and files that have

Is there a way to retrieve JSON data only for clicked buttons and uploaded files? Currently, I am receiving all button values, whether clicked or not, in one instance, and file paths with fake paths like C:\\fakepath\\test.txt in anothe ...

`The file cannot be modified at this time`

I am having an issue with updating a file using fs and then creating a zip in a different location. The file update seems to be working fine, but the zip file does not have the updated contents. Can someone point out what I am doing wrong in my code belo ...

Assistance required with a project involving JAXB

Can someone assist me with a problem I am facing in JAXB? Every time I try to run the project, I encounter the error message shown below: Property assignment is present but not specified in @XmlType.propOrder this problem is related to the following locat ...

Tips for sending multiple values in separate lines through the sendKeys() function within a text box

Is there a way to input multiple words on separate lines into a text box? I'm looking for a solution. Desired result : 13456,Teena 12378,Tesa 130987,Jhon ...

Ways to avoid submitting based on the outcome of AJAX requests

When working on an ASP.NET MVC Project, I encountered an issue where I wanted to prevent a button from submitting if the result returned from an AJAX call was false. However, no matter what I tried, the button always triggered the submission. Below is th ...

Obtaining data from one form to validate on the web in Lotus Notes

I have a radio button field on my custom form in Lotus Notes. When the radio button is selected as "Yes", it reveals a hidden link. Clicking on this link opens another form. If "Yes" is still selected in the main form, specific fields on the second form ...

Enforce directory organization and file naming conventions within a git repository by leveraging eslint

How can I enforce a specific naming structure for folders and subfolders? I not only want to control the styling of the names (kebab, camel), but also the actual names of the folders and files themselves. For example, consider the following paths: ./src/ ...

Where can I find the documentation for Apache Hadoop's build artifacts?

As a beginner in Apache Hadoop, my initial goal is to run a simple "hello world" application. The first step is to set up the development environment and compile the code. Currently, I am working on compiling classes from a MapReduce job example in a Hadoo ...

Is a default package created when a new Java project is made in Eclipse?

As someone new to Java, I have primarily been relying on YouTube and various tutorials online to learn the ins and outs of Java. My IDE of choice is Eclipse Neon 3. I've noticed that in a lot of these tutorials, when a new project is created, a packa ...

Trouble is arising in rendering events with years before 100 (specifically years 0000 - 0099) when using the ISO8601 format in fullCalendar

I've created a Calendar that showcases various events using fullcalendar. The events span from the years 0001 to 6000. Fullcalendar requires dates in ISO8601 format, and I am providing them as such. Events from the years 0100-6000 render perfectly w ...

Receiving all alerts simultaneously

I'm currently facing an issue with setting notifications using the alarm manager for events. If I set multiple notifications at different times, it seems that all notifications trigger at the last specified time for notification. Additionally, I want ...

Accessing and sending only the body part of an HTTP response in Angular 7 test cases: A comprehensive guide

Currently, I am working on creating unit test cases in Angular 7 for a Component that utilizes an asynchronous service. This is the content of my component file: submitLoginForm() { if (this.loginForm.valid) { // send a http request to save t ...

Analyzing a server's log data at regular intervals

Currently, I am working on a project where I need to parse a server log file using JavaScript every 24 hours and then store the extracted information in a MongoDB database. The process of parsing the data and storing it is what I find to be the most chall ...