Uploading a file using Selenium WebDriver and jQuery integration

Imagine a webpage containing the following element:

<div class="block-title-inside">
     <a href="javascript:void(0);" class="block-title-link fright" style="display:block; overflow: hidden; width: 105px;">Upload video <span class="blue-arrow-right"></span>
     <input type="file" name="file" id="videoUpload" class="dpt-mediafile-input-button" style="z-index: 999"></a>
Videos</div>

The issue arises when a user clicks on the "Upload video" button above, as there is no "Attach" button, resulting in the native OS window opening for file selection.

Efforts to upload a file using Selenium WebDriver have proven unsuccessful with simple code snippets like:

driver.findElement(By.id("videoUpload")).sendKeys("D://Other//sample_videos//barsandtone.FLV");
driver.findElement(By.id("videoUpload")).click();

This problem appears to be linked to the site's utilization of a jQuery upload script. Here are the pertinent sections of JavaScript code:

  1. (restricted access for guest users)
  2. Separate links for: http://www.dailypreptalk.com/components/com_dpt/assets/file-upload/js/jquery.fileupload.js, http://www.dailypreptalk.com/components/com_dpt/assets/file-upload/js/vendor/jquery.ui.widget.js

Attempts to trigger JavaScript using:

js.executeScript("document.getElementById('videoUpload').value = 'D://Other//sample_videos//barsandtone.FLV'");
js.executeScript("document.getElementById('videoUpload').click()");

Yielded no positive outcomes. Similar efforts were made with jQuery initialization but to no avail:

js.executeScript("dpt.jQuery('#videoUpload').value = 'D://Other//sample_videos//barsandtone.FLV'");
js.executeScript("dpt.jQuery('#videosModal').modal('show');");

The challenge remains in understanding how to set up the jQuery upload widget with a pre-filled file path.

Your assistance is greatly appreciated!

Answer №1

The answer was discovered utilizing Robot functionality:

import java.awt.*;
import java.awt.event.KeyEvent;

Here is the original code along with the file path to D:/1.avi:

driver.findElement(By.id("videoUpload")).click();
  driver.getWindowHandle();
  //type path to your file using robot VK language
  try {
      Robot r = new Robot();
      r.keyPress(KeyEvent.VK_D); //D character
      r.keyPress(KeyEvent.VK_SHIFT); // colon character
      r.keyPress(KeyEvent.VK_SEMICOLON); // colon character
      r.keyRelease(KeyEvent.VK_SEMICOLON); // colon character 
      r.keyRelease(KeyEvent.VK_SHIFT); // colon character
      r.keyPress(KeyEvent.VK_BACK_SLASH); // backslash character etc
      r.keyPress(KeyEvent.VK_1);
      r.keyPress(KeyEvent.VK_PERIOD);
      r.keyPress(KeyEvent.VK_A);
      r.keyPress(KeyEvent.VK_V);
      r.keyPress(KeyEvent.VK_I);
      r.keyPress(KeyEvent.VK_ENTER);
  } catch (AWTException e) {
      e.printStackTrace();
  }

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

The backward navigation in Chrome leads to an incorrect webpage

With my current use of NodeJS, I have a function in place that requests content from the server and displays it on the browser as a complete HTML page. However, there seems to be an issue with Chrome where if I follow these steps, the original page is ski ...

Invoking an HTML popup within a JavaScript function

Here is a question. In my project, I have the following JavaScript function: <script type="text/javascript" language="javascript"> $(document).ready(function(){ PopUpHide(); }); function PopUpShow(popup_title, pk_post_add){ document.getEl ...

What is the best way to elegantly finish a live CSS animation when hovering?

Currently, I am working on a planet orbit code where I want to enhance the animation speed upon hover. The goal is for the animation to complete one final cycle at the new speed and then come to a stop. I have been successful in increasing the speed on hov ...

Calculate the total amount by multiplying the price and quantity values within nested arrays

I have a collection of objects with nested arrays structured like this [ { orderId: 123, orderStatus: 'Pending', date: 'June 13, 2020', products: [ {product: 'choco', price: 300, qty: 3}, {product: 'm ...

The retrieval of data using an Ajax call to a servlet from a JavaScript function is not successful in returning a value

My goal is to load a map with markers on a website. When I trigger the servlet from JavaScript code outside a function, I successfully retrieve the values (coordinates for marker display). However, when I encapsulate the servlet call within a function and ...

Send a PUT request using Ajax

I am a beginner when it comes to Ajax requests and I have crafted the code shared in this Pastie. On line 107, my $.PUT function is causing an error in Firebug stating that $.PUT is not a recognized function. I acknowledge that there are issues with my aja ...

Executing filepicker.io Javascript API calls may lead to unsafe errors in Javascript

I am currently using AngularJS and encountering an issue when trying to call filePicker.pickAndStore from my Upload controller. Every attempt to use a filepicker.io API function triggers an "Unsafe Javascript attempt" error: The frame requesting access ...

Curious about the power of jQuery methods?

I've been coming across codes similar to this: $(document.documentElement).keyup( function(event) { var slides = $('#slides .pagination li'), current = slides.filter('.current'); switch( event.keyCode ) { ...

Issues with Angular ng-model-options not working properly in Internet Explorer

Is there a way to submit a form on keypress/enter while using ng-model-options="{updateOn: 'submit'}" Here is the template: <form ng-model-options="{ updateOn: 'submit' }"> <input type="submit" value="submit" style="visib ...

Troubles with Express JS session handling

I've encountered a challenge with sessions in my Express app. After a successful login, the code should direct the user to the 'dashboard' page by default if no specific URL is requested. The login.js file sets req.session.user to a user i ...

Using GraphQL in React to access a specific field

Here is the code snippet I am working with: interface MutationProps { username: string; Mutation: any; } export const UseCustomMutation: React.FC<MutationProps> | any = (username: any, Mutation: DocumentNode ) => { const [functi ...

Utilize an asynchronous method to upload files to Google Cloud Storage in a loop

I am new to using Javascript and have been working on a loop to upload images to Google Cloud Storage. While the image uploads correctly with this code, I'm facing an issue where the path (URL) is not being saved in the database AFTER the upload. I a ...

Tips for preventing "Undefined" errors when retrieving data in Vue

I am currently working on a basic page that displays data fetched from the server. Here is the setup: <p>Customer's name for the order: {{ order.customer.name }}</p> Javascript: export default { data () { return { order: {} } }, ...

When the page is fully loaded, I am trying to utilize jQuery with functions like $(window).ready(), but unfortunately, it does not seem to be functioning as expected

Utilizing jquery to dynamically adjust the content on my html page based on the page width. Upon the page being fully loaded (using the $(document).ready(function({\\there is some code here!}));), I aim to execute certain functions. My objectiv ...

Utilizing D3.js v4 to showcase a JSON file on a map

I am attempting to create a map similar to the one created by Mike Bostock. You can access my JSON file (here), which represents Europe divided into NUTS 2 regions. The structure of the JSON file is as follows: { "type": "Topology", "objects": ...

Creating new DOM elements based on the value of an input

I am currently working on a function that adds elements to the DOM based on the value entered into an input element. However, every time a new value is inserted, the previous elements are erased and replaced with the new ones. My goal is to find a way to ...

Scrolling horizontally using jQuery and CSS

I have been experimenting with creating a horizontal scrolling page that moves to the right when scrolling down and to the left when scrolling up. Here is the current code: HTML <div class="scroll-sections"> <section id=&quo ...

Tips for integrating JSON information into nvd3 visualizations

I am a newcomer to Javascript and am struggling to identify the error in my code. My current project involves utilizing NVD3 charts, specifically a time series chart that displays dates along with the closing prices of a specific stock. The dataset spans f ...

Issues with Kendo Grid showing incomplete data and columns

Having trouble populating a kendo grid with column titles, as some columns appear empty despite having data when checked in the console log. $(function () { $("#uploadBtn").click(function () { var url = window.rootUrl + 'Upload/UploadM ...

localization within vue component

if (self.form.pickupTime == '') { self.formError.pickupTime = 'Please enter a pickup time that is ready for collection.'; status = false; return status; } else { self.formError.pickupTime = ''; } I am struggling ...