Using AJAX in JavaScript, learn how to send an array of base64 images to Java in a single call

My application allows users to upload multiple images simultaneously.

Once uploaded, all image sources are stored in an array and sent using an ajax call.

Unfortunately, the ajax call returns an error stating that the size of the data is too long.

Below is a snippet of my code:

function save_domain_images(base64ImageSrc){
  var datastring = "&token="+domainImgSaveSession+"&imgSrc="+base64ImageSrc+"&action=saveDomainImg";
  $.ajax({
    type : "POST",
    url : base+"/AppUserListServiceProvider",
    data : datastring,
    cache : false,
    success : function(data){
      data                      = JSON.parse(data);
      domainImgSaveSession      = data["randomNew"];
      if(data["error"] == null && data["croppedImg"] != null){
        console.log("data : "+data["croppedImg"]);
      }
    },
    error : function(){}
  });
}

Answer №1

function convertBase64ToBlob(base64String) {
  const match = /^\s*data:([\w/]+)(?:;base64)?,/.exec(base64String);
  const type = match[1];
  const blob = createBlobFromBase64(base64String.slice(match[0].length), type);
  const formData = new FormData();
  formData.append('image', blob, name);

}

function createBlobFromBase64(base64) {
  const decodedCode = window.atob(base64.split(",")[1]);
  const arrayBuffer = new window.ArrayBuffer(decodedCode.length);
  const uint8Array = new window.Uint8Array(arrayBuffer);

  for (let i = 0; i < decodedCode.length; i++) {
    uint8Array[i] = decodedCode.charCodeAt(i);
  }

  const BlobBuilder = window.WebKitBlobBuilder || window.MozBlobBuilder;
  if (BlobBuilder) {
    const builder = new BlobBuilder();
    builder.append(arrayBuffer);

    return builder.getBlob(format);
  } else {
    return new window.Blob([arrayBuffer], {
      type: format
    });
  }
}

Finally, the formData can be posted with the image blob.

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

Initiate several asynchronous requests every second

I am trying to create a chat system similar to Facebook chat :) Currently, I'm using the following requests: To Retrieve Room Users And Room Body $('.room_users,.room_body').each(function () { var page = $(this).attr(" ...

Pagination and asynchronous deletion with will_paginate

Currently, I have a list of resources that are displayed on a paginated list using the will_paginate gem. I haven't made any customizations yet, here is how my view looks: <ul> <%= render :partial => "item_li", :collection => @items%& ...

Issue with URL parameter in React when using React Router

Initially, everything was running smoothly in my React project using react-router-dom. However, once I added another Route like so: <Route path="/edit/:id" component={EditPage}/> and tried changing the URL in the browser to http://localhos ...

Loading options dynamically in a dropdown list using KnockoutJS

I am new to KnockoutJS and I have successfully worked with static data in dropdown lists. Now, I need to dynamically populate the dropdown list from a controller. 1. I want to retrieve a dynamic list from my controller and populate it in a dropdown list. ...

Using cannonjs and Three.js to connect a physics body with a visual mesh

I have written the code below to create two spheres using cannonjs with Three.js for rendering. var world, mass, body, shape, timeStep=1/60, camera, scene, renderer, geometry, material, mesh; initThree(); initCannon(); animate(); func ...

The test does not pass when attempting to use a shorthand operator to ascertain the truthfulness of

I've encountered an interesting issue with my unit test. It seems to work perfectly fine when I directly return true or false, but fails when I try to use a shorthand method to determine the result. Let's say I have a function called isMatched w ...

Turning off "webdriver='true'" in Firefox with Selenium

Currently, I am utilizing Selenium with Java (through Firefox) for carrying out automated tasks. It has come to my attention that Selenium inserts webdriver="true" into the HTML code, making it easy to detect. My query is regarding how I can turn off this ...

Press the button to activate the function

<table class="calc" cellpadding=2> <td><input type="button" class="calc" id="screen" value="0" ></td> <td><input type="button" class="calc" id="screen" value="0" ></td> <tr> </ ...

Custom Component in React Bootstrap with Overflowing Column

I am working on a custom toggle dropdown feature in my React application: import React from 'react'; import 'react-datepicker/dist/react-datepicker.css'; const DateRange = props => ( <div className="dropdown artesianDropdo ...

The Axios request for the concatenated URL is failing to execute

Encountering an issue with Axios in node js. Here's the code snippet: let callResult = await axios.get(urlData, config) The configuration object used is as follows: let config = { headers: { 'X-Token': token } ...

In Javascript, we can increment the current date by utilizing the `getDate()`

I am trying to create an if statement in JavaScript; if (nextProcessingDate > today ) { //do something } nextProcessingDate has a timestamp assigned, like 09/07/2014 12:10:17 To assign today's timestamp to the today variable, I am using this c ...

What about connecting mapStateToProps with a specific ID?

Currently, I have a basic function that fetches all Elements const mapStateToProps = ({elements}) => { return { elements: getElementsByKeyName(elements, 'visibleElements'), }; }; I want to modify it to something like this c ...

How to add an ajax form element in Drupal 8 after an ajax callback has been

Currently, I am working on developing a Drupal form that involves multiple AJAX-enabled form elements. The issue I am facing is related to a select list that triggers an AJAX callback upon selection. When this happens, a new select list is added to the pa ...

Tips for arranging, categorizing, and separating the array in alphabetical order using Angular 2+

I am looking to organize the buttons' content alphabetically into groups A-H, I-Q, and R-Z. The code I'm using is in Angular2+. https://i.sstatic.net/pPCBO.png My array: this.dropdownList = [ { item_text: 'Organisation' }, ...

What is the best way to transfer information between two separate Javascript controller files?

My current situation is a bit complex, but I believe there must be a straightforward solution. I have two Javascript controller files: one named rootPageClient.js and another called findPollClient.js. Additionally, there's a file called ajax-function ...

Removing Click event upon button click - Implementing Vue and Vuetify

In my project using Vuetify, I have implemented a dialog that opens when a button is clicked. The dialog can be closed after completing the required actions. However, in the production environment, the dialog cannot be reopened more than once due to the re ...

What is the memory allocation for null values in arrays by node.js?

Continuing the discussion from this thread: Do lots of null values in an array pose any harm? I experimented with node.js by doing this: arr=[] arr[1000]=1 arr[1000000000]=2 arr.sort() However, I encountered the following error: FATAL ERROR: JS Alloca ...

Utilize .map function to format a date string and generate a table

I am currently utilizing .map along with React in order to generate a table using a coupons object. My goal is to format a date string into the "mm/dd/yyyy" format, with coupon.starts_at typically being set as coupon.starts_at = "2013-08-03T02:00:00Z" I h ...

Struggling with integrating jQuery append into Backbone.js

Having trouble using jQuery.append() and backbonejs. Currently, when attempting to append, nothing happens (except the jQuery object is returned in the immediate window) and the count remains at 0. Manually adding the element has not been successful. I als ...

AngularJs - Customizable dynamic tabs that automatically adapt

Below is the HTML code snippet: <div> <ul data-ng-repeat ="tab in tabs"> <li data-ng-class="{active: tab.selected == 'true'}" message-key="Tab"> </li> </ul> </div> As shown ...