Tips for transferring an array of images to a controller via ajax

Purpose: To convert the image array items into an input list and send them to the controller.

Below is the JavaScript code that selects and modifies images:

    const output = document.querySelector("output");
    const input = document.getElementById("roUpload");
    let imagesArray = [];

    input.addEventListener("change", () => {
      const files = input.files
      for (let i = 0; i < files.length; i++) {
        imagesArray.push(files[i]);
      }
      displayImages();
    })

    function displayImages() {
      let images = ""
      imagesArray.forEach((image, index) => {
        images += `<div class="image">
                    <img src="${URL.createObjectURL(image)}" alt="image">
                    <span onclick="deleteImage(${index})">&times;</span>
                  </div>`
      })
      output.innerHTML = images;

    }

Now, here are the codes for sending to the controller:

     var fileData = FormData();

     function SendImage(){

            **var files = output.files;**

            for (var i = 0; i != files.length; i++) {
                fileData.append("files", files[i]);
              }

            $.ajax(
            {
                type: "POST",
                url: "/ChinaProblemsReport/SendImage/",
                contentType: false, // Not to set any content header
                processData: false,
                data: fileData,
            });

            $(document).ajaxStop(function(){
                    window.location.reload();
            });
    };

Additionally, here are the HTML codes:

<input type="file" id="roUpload" multiple="multiple" accept="image/jpeg, image/png, image/jpg" />

<output></output>

I am facing no issues in sending to the controller, my concern lies in how to populate the files in the SendImage() function with the images from the output.

Your assistance is appreciated. Thank you.

Answer №1

To get only the src values, follow the code snippet below:

            //parse and extract image sources from output
            var filesList = output.querySelectorAll('img');
            var sourceURLs = [];

            for (var j = 0; j != filesList.length; j++) {
                sourceURLs.push(filesList[j].src);
            }
            fileData.append("files", sourceURLs);

This method has not been tested yet, so there might be issues when you try it out. In case you encounter any errors, feel free to reach out with details.

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 computer system encountered an issue in computing the values of the text

Possible Duplicate: Unable to get textfield value using jQuery My current project involves updating input fields based on user changes in quantity for items. Each item is retrieved from a database and I am generating invoices for customers. However, ...

Is it possible to determine the optimal dimensions for a viewbox that would accommodate all the elements of a drawing?

In the event that a drawing contains multiple shapes and paths, where all of these elements need to be fully visible without any cropping, the viewbox must encompass everything. Yet, is it possible to identify the specific values for min-x, min-y, width, ...

"JQuery AJAX loop is not properly iterating through values and only returning

Struggling with the logic in my ajax calls where the array var log keeps getting overwritten by each subsequent call. I need a way to modify the code so that it appends the next array instead of replacing it. $.ajax($.extend({}, ajaxDefaults, source, { ...

Ways to eliminate whitespace in React and Bootstrap 5

I have a pet project that requires mobile responsiveness, and I'm encountering an issue with white space in the Carousel component. I am unsure of how to remove it - can anyone provide assistance? Here is how the page looks on PC: https://i.sstatic.n ...

steps to eliminate a cookie upon second click

I have successfully implemented a feature where the color of a button is stored in a cookie, so that when the button is clicked, the CSS color remains even after page refresh. However, I am struggling to figure out how to destroy the cookie after the secon ...

Can we incorporate modulo into the loop?

I have a JavaScript function with HTML code inside. I need the ".one-card" div to repeat four times within each ".row" div. The ".row" div is being repeated in a foreach loop. I want to check if the result of modulo (4) is not equal to zero, then display t ...

Chaining multiple ajax calls in jQuery is a powerful technique that allows you

I am looking to execute a series of N ajax requests without causing the browser to freeze, and I intend to utilize the jquery deferred object for this purpose. Below is a sample scenario involving three requests, but in reality, my program might need to h ...

Verify the existence of the linked page's href url

Is there an elegant way to verify if a hyperlink on a website directs to a page that returns an HTML 200 code? I'd like to give users the ability to input their own links in a model, but I also want to block any links leading to a 500 or 404 error pag ...

Attempting to align CSS with JavaScript for seamless integration

Seeking guidance on how to convert CSS from a stylesheet into inline styles directly within an HTML document using JavaScript. The search results I've found so far have been somewhat irrelevant to what I'm looking for. To clarify, I am looking f ...

Creating a drop-down menu within an HTML table along with a D3 bar chart

How can I implement a drop-down menu allowing the user to choose a time interval for this HTML table and d3 bar chart? The time intervals needed are: Now, 24 hours, 48 hours, 72 hours, 1 week, and 1 month. I am relatively new to creating dynamic tables and ...

Hiding labels in an HTML document can be achieved by using CSS

Recently, I've been working on a code that relies on a specific Javascript from Dynamic Drive. This particular script is a form dependency manager which functions by showing or hiding elements based on user selections from the forms displayed. Oddly ...

Using Jquery Ajax in CodeIgniter to verify the existence of an image

Is there a way to check if an image exists on the server file system and have the list of files stored in a database? I am trying to make an AJAX call for validation and then display the result on the screen with an append effect. Here is my code, but it d ...

Guide on positioning a div to float from bottom left to top right using CSS as the window screen size is reduced

I am wondering if it is possible to float the div using CSS in the following manner. My goal is to have CSS DIV 2 move under CSS DIV 1 to the right when the window size is reduced. Please refer to the screenshot below: On larger window sizes, three DIVs a ...

What is the best way to choose an HTML element based on the attributes of its child nodes in CSS?

Take this scenario for instance: <tr> <td align="center">123</td> <td class="someclass">abc</td> </tr> My goal is to target all <tr> elements that contain a <td> with the class attribute set to someclass. ...

Why does this function properly on every browser except for Opera?

I have implemented a script that allows me to replace the standard file upload input with a custom image. The script also ensures that an invisible 'browse' button appears underneath the mouse pointer whenever it hovers over the custom image. Thi ...

Difficulty with float left in HTML/CSS causing divs to appear below each other instead of side by side

I'm currently facing an issue with creating a 2 column layout using the classes "left" and "right". Right now, the .right column is not floating left and is instead appearing below the .left column. Interestingly, when I delete the content inside .le ...

Understanding the process of extracting map data from JSON files

I am currently working with Spring 3 and JQuery. My goal is to retrieve a Map containing element IDs and their values from my Spring Controller, and then use this data to update the View. Below is a snippet of the Controller code: @RequestMapping(value= ...

Error: Disappearing textarea textContent in HTML/TS occurs when creating a new textarea or clicking a button

I've encountered an issue with my HTML page that consists of several textareas. I have a function in place to dynamically add additional textareas using document.getElementById("textAreas").innerHTML += '<textarea class="textArea"></text ...

How do I insert a variable into my email content using PHP?

Hey there, I have a form that captures Name, Email, Subject, Telephone Number, Message, and a checkbox. Unfortunately, I'm not very proficient in PHP. I've just started learning the basics and could use some guidance from you :) The Form < ...

Implement conditional logic in jQuery for optimal code execution

Currently, I am in the process of updating my website: One interesting feature is that when you click on an image to select a project, the requested WordPress project page loads dynamically within the existing page and the URL changes to include a hash li ...