Automate the process of uploading images using Selenium, without the need for AutoIt

My company's website features a unique image upload button that differs from the traditional input type file. I'm looking for an automated way to upload images using this button without relying on tools like AutoIt to interact with the file explorer.

Here is a snippet of the HTML code for this particular button:

<button ng-click="onClick()" ng-disabled="readOnly" accepted-types="image/*" on-files-selected="onFilesSelected" allow-multiple="true" readonly="readonly">Add images</button>

Since this button does not use the standard input element, such as <input type="file">, and instead utilizes AngularJS, I am unable to use Selenium's sendKeys() function to input the image file location from my machine.

I am exploring possible hacks or workarounds for uploading the image, such as overriding the onClick() function to read from a specified location (although this approach seems impractical), or intercepting the event that triggers the file explorer opening in order to find a solution. However, these methods are experimental and unsupported.

I am curious if utilizing another browser automation tool, such as Microsoft's Playwright, could provide a solution to this challenge.

Answer №1

Utilize JACOB, a tool that offers Java Native Interface compatibility to integrate AutoIt functions with Selenium. I have successfully implemented this solution in various applications like MSTeams and Slack for automating tasks such as file uploads.

Essential Steps Before Implementing the Code:

Step 1: Download the JACOB jar file

Step 2: Register the AutoIt COM libraries by running the command e.g regsvr32 AutoItX3_x64.dll

Required Components for Integration:

  • jacob.jar
  • AutoItX4Java.jar
  • jacob-1.18-x64.dll
  • jacob-1.18-x86.dll

Sample Code snippet:

[This Code Provides Interaction with File Explorer]


import com.jacob.com.LibraryLoader;

import autoitx4java.AutoItX;

public class Attachments {

   public void uploadAttachments(){

        File f = new File("Location");
        File[] fil =f.listFiles();

        //Upload Button Xpath
        WebElement uploadFromComp = driver.findElement(By.xpath("//span[contains(text(),'Upload from my computer')]"));
        uploadFromComp.click();
        Thread.sleep(5000);

        String jacobDllVersionToUse;
        if (jvmBitVersion().contains("32")) {
            jacobDllVersionToUse = "jacob-1.19-x86.dll";
        } else {
            jacobDllVersionToUse = "jacob-1.19-x64.dll";
        }

        File file1 = new File("registerAutoItDll", jacobDllVersionToUse);
        System.setProperty(LibraryLoader.JACOB_DLL_PATH, file1.getAbsolutePath());

        AutoItX x = new AutoItX();
        x.winWaitActive("Open");
        x.sleep(5000);
        x.send(fil[j].getAbsolutePath());
        x.send("{ENTER}", false);
}}

Feel free to give it a try and let me know how it goes!

Answer №2

With Playwright, uploading files is incredibly easy and much simpler compared to Selenium.

// Upload a single file
await page.setInputFiles('input#upload', 'myfile.pdf');

// Upload multiple files
await page.setInputFiles('input#upload', ['file1.txt', 'file2.txt']);

For more information, visit:

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

Sending information through AJAX in Elgg

Is there a way to transfer information between two PHP files using AJAX with Elgg? data_from_here.php <?php $entity = elgg_extract('entity', $vars, FALSE); $guid = $entity -> guid; require_js('javascript_file.js'); ...

Using ng-model to create association between a select box and ng-repeat to populate its options

Here is a Plunker link demonstrating my problem. I have an object that includes a division property. The issue is, there is no division_id in the object, but to set or update the division, I need to set the division_id field. Here's an example of the ...

Displaying a variable in a text box using the italicized format

Could you please share how to display a variable in a textbox using italics style? Appreciate your help! ...

I am attempting to verify a user's login status with Next.js and Supabase, however, I am encountering difficulties in making it function properly

I recently cloned this repository from https://github.com/vercel/next.js/tree/canary/examples/with-supabase-auth-realtime-db and I'm trying to implement a navigation bar that changes based on the user's login status. Unfortunately, the code I&ap ...

"Utilizing Date Labels on the X-axis in Google Chart API: A Step-by-Step

Is it possible to create a chart using Google Chart API where the X-axis values represent the days in a month? I have a set of data points that are not evenly distributed. For example: Date - Value 1/1/2009 - 100 1/5/2009 - 150 1/6/2009 - 165 1/13/2009 - ...

Display a vibrant welcome screen on an Android WebView that ensures a visually appealing experience while the content loads for the

When launching an application, the desired behavior is as follows: Display a splash screen while simultaneously loading a URL Upon the firing of a JavaScript interface event on page load, remove the splash screen Mainactivity.java myWebView.addJavascript ...

Tips on altering a predetermined input text value using JavaScript

I have a question about using JavaScript. I am currently developing a tax calculation system. function calculateTax(){ var invoiceValue = document.getElementById("invoicevalue"); var ppn = document.getElementById("ppn"); var pph = document.get ...

What is the most efficient way to condense multiple repetitive case statements?

Within my code, I have multiple case statements that are quite similar, with the only difference being the argument 'key' from the function click(key). The variable 'c' is represented as JSON. The challenge lies in incorporating the ar ...

Develop a function that transforms a provided string

I need assistance creating a function that will convert a given string into the specified output format shown below: // Input const optionRule = '{1069} AND ({1070} OR {1071} OR {1072}) AND {1244} AND ({1245} OR {1339})'; // Output Example /* co ...

Rendering data in React using the array indexRendering data in React

I'm encountering an issue in React JS where I need to display all data from a REST API with a numeric index. REST API: [ { "id": "1", "start_date": "2020-05-08 09:45:00", "end_date": "2020-05-08 10:00:00", "full_name": "mirza", "cust_full_name": "fu ...

The bootstrap navbar dropdown feature isn't functioning properly on iPhones

Currently utilizing "bootstrap": "~3.3.4" within the mean.js framework, I am facing an issue with the navbar dropdown menu. On desktop, everything functions as expected - the dropdown opens and remains open when the icon is clicked. However, once deployed ...

Updating the state of a React Component using data from 2 input fields

I am facing an issue with two input fields of type "file" in a React component. My goal is to load a JSON file into each input field, save the data from both files into separate variables, and update the state of the component. However, I have noticed that ...

Integrating dependencies within an Ember model

Looking to inject dependencies into my Ember models. https://github.com/emberjs/ember.js/issues/3670 mentions that this feature is disabled. To enable MODEL_FACTORY_INJECTIONS, there is a guide at https://github.com/stefanpenner/ember-cli/blob/master/blue ...

How to Develop a Custom getText() Function for a Selenium Element?

Creating a custom Selenium getText() method that can retrieve either the node text or the node plus child text of an element is my current challenge. The default behavior of Selenium appears to utilize the Xpath .//string() method which includes the text o ...

Issue: $injector: provider is not recognized

My project: angular.module('project').factory('httpService', function ($http, $state, $scope, $rootScope, $q, $localStorage) { /*some code*/ return httpService; }) My view, angular.module('project.dashboard') .control ...

`How can the background color be altered based on specific conditions?`

I am attempting to modify the background color. My goal is to change every odd result to a light green (#f0f5f5) to avoid a large white space when the result ends in an even number. I would also like to change the background color of the pagination section ...

Adding style tags dynamically to a component and then encapsulating the styles again (using Angular)

Currently, I am in the process of upgrading from AngularJS to Angular. Our app is currently a hybrid one being bundled up with webpack instead of just angular cli. Due to this setup, we have encountered issues where our css or scss files are not correctly ...

Changing a field in AngularJS to set validity as true in a different way

After following the guidance provided in this answer to implement custom server-side validation for a unique email constraint, I encountered an issue with my submit function on the controller: function submit(form){ CompanyUser.save(vm.model) .suc ...

Display content from an external HTML page within a div using Ionic

Currently, I am facing an issue where I am utilizing [innerHtml] to populate content from an external HTML page within my Ionic app. However, instead of loading the desired HTML page, only the URL is being displayed on the screen. I do not wish to resort t ...

Ensuring state is updated once an action has been completed | React and Redux

My application relies on retrieving data from an API and operates as a CRUD application. One of the functionalities involves deleting an item from a list, and here is the corresponding action: import axios from 'axios' export function removeUse ...