"Incorporate an image into the data of an AJAX POST request for a web service invocation

I have been attempting (with no success thus far) to include an image file in my JSON data when making a call to a method in my webservice.

I have come across some threads discussing sending just an image, but not integrating an image within a JSON data object.

The call functions as expected if I keep "imageFile" as null.

$("#butSubmit").click(function(){

var files = document.getElementById('files').files;
var file = files[0];

        $.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url:"http://localhost:8080/SampleApp/api/users/add",
data: JSON.stringify({"description":"test2","title":"testest2","uploaderName":"seren","imageFile":file})    
  });
});

On the web service side, I am utilizing this method:

@Path("/add")
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public void addUser(Picture picture){

        userService.persistPicture(picture);

    }

and this constructor for the Picture class:

@JsonCreator
   public Picture(
            @JsonProperty("description") String description,
            @JsonProperty("title") String title,
            @JsonProperty("uploaderName") String uploaderName,
            @JsonProperty("imageFile") byte[] imageFile) {
        this.uploaderName = uploaderName;
        this.title = title;
        this.description = description;
        this.imageFile = (byte[]) imageFile;
    }

Your guidance on this matter would be greatly appreciated!

Thank you in advance!

Answer №1

Utilize the capabilities of the FileReader object provided in JavaScript's HTML 5 File API (check browser support)

    var files = [];

    $("input[type=file]").change(function(event) {
      $.each(event.target.files, function(index, file) {
        var reader = new FileReader();
        reader.onload = function(event) {  
          object = {};
          object.filename = file.name;
          object.data = event.target.result;
          files.push(object);
        };  
        reader.readAsDataURL(file);
      });
    });

//send file via AJAX call
$.each(files, function(index, file) {
    $.ajax({url: "/ajax-upload",
          type: 'POST',
          data: {filename: file.filename, data: file.data},
          success: function(data, status, xhr) {}
    });      
  });

On the server side, you will receive a base64 encoded value that can be easily converted to binary.

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 JSON validator effectively verifies all types of string inputs

Schema for Root: { "$schema": "https://json-schema.org/draft/2020-12/schema", "properties": { "deviceId": { "description": "Unique identifier of the device in UUIDv4 format& ...

Determine the precise boundaries of the React component

I am working with a basic ellipse element: <span style={{ width: /*someWith*/, height: /*someHeight*/, borderRadius: "50%" }}/> and, I am using getBoundingClientRect() to retrieve its bounds (displayed in blue). https://i.ssta ...

How to link an image from a location outside the src folder in an Angular project

I am currently working on an online store project, and I have a specific issue with my image files being stored outside the src folder. The path to the images is within the flowersApp folder under img Is there a way for me to access these images from this ...

Why Isn't AJAX Displaying the Output from PHP?

Currently, I am implementing ajax to display a string received from a php file. This particular php file is generating rows for an html table. My goal is to have ajax place these rows within a with a specific id that resides inside a and I want this oper ...

Is the jqm flipswitch with the label on the left and the switch on the right?

My goal is to display multiple flipswitches on a mobile app page. This is the code I am using: <div class="ui-content"> <form> <fieldset> <div data-role="fieldcontain"> <label for="checkbox-based-flipswitch" ...

Activate the feature of smooth shading using Three.js

When rendering an object with textures using MTL and OBJ files in Three.js, I encountered an issue where my model was displayed with flat shading. How can I enable smooth shading? var scene = new THREE.Scene(); var mtlLoader = new THREE.MTLLoader(); mtl ...

How to convert a nested array of objects into a string using JavaScript for passing as a URL parameter

So, I'm dealing with a nested JSON array of objects here. My goal is to pass it as a parameter in the URL and then save it to my MongoDB database. However, when I tried doing that, it ended up being saved as [object object]. Does anyone know how to so ...

Starting http-server in the background using an npm script

Is there a way to run http-server in the background using an npm script, allowing another npm script, like a Mocha test with jsdom, to make HTTP requests to http-server? To install the http-server package, use: npm install http-server --save-dev In your ...

Utilizing JSX interpolation for translation in React JS with i18next

I am trying to utilize a JSX object within the interpolation object of the i18next translate method. Here is an example code snippet along with its result: import React from "react"; import {useTranslation} from "react-i18next&qu ...

Access to the android.permission.READ_PHONE_STATE has been refused

I am encountering an exception stating that permission is denied to use getDeviceId(), despite having android.permission.READ_PHONE_STATE in my manifest file. The exception message reads: getDeviceId: Neither user 10055 nor current process has android.pe ...

Performing aggregation functions on arrays of JSON data in PostgreSQL

Many discussions mention using json_array_elements to extract elements from a JSON array, but it seems to only work on a single array. When attempting to use it in a general query, an error occurs: ERROR: cannot call json_array_elements on a scalar Cons ...

Ways to extract information from a dynamically generated table

I'm facing an issue with retrieving data from a dynamically generated table within my script... Here is the code snippet: $('#update_panel').html('Loading Date....'); $.ajax({ url: '/Home/GetCountries', type: & ...

I have just developed a Java test script using Eclipse, and now I am looking to execute it on a headless Linux CentOS VM. How

Looking for guidance on running successful test scripts created using Eclipse on a Windows system in a Linux VM via SSH. Despite numerous attempts following online instructions, I have not been able to achieve success. It seems changes might be needed in t ...

Update the array with the new data by setting the state

Is it possible to edit and save data in an array while iterating through it using this.state.data.map()? If so, what is the best approach to achieve this? Check out this live example for reference. Below is a sample code snippet: class App extends React ...

Is there a way to capture the click event of a dynamically generated row within a panel?

Could you please advise on how to capture the click event of a row that is generated within a panel? I have successfully captured events for rows generated on a page using the , but now I need assistance with capturing events from rows within a panel. I c ...

Show information from an array

On the index.php page, there is a script that retrieves data from demo.php and presents the outcome in a div. <div class="leftbox"> <?php echo "<div id='proddisplay'>"; echo "</div>"; ?> </div&g ...

Struggling to get the jQuery resize event to function properly

Ensuring that my charts remain responsive on different devices has been quite a challenge. Despite implementing a resize event handler in my function to dynamically adjust the charts, I encountered an issue where the page would go blank upon resizing the b ...

Removing a Dom element using stage.removeChild( )

When the number 6 is typed and entered into the game, the function correct() in the code snippet below determines what action to take. I would like to remove the DOM element gg (the equation 3+3=input) from the stage after typing 6 and pressing enter. How ...

Fixed position toolbar within a container positioned beside a dynamically sized sidebar navigation

I'm trying to figure out how to create a fixed toolbar that fills the remaining width of the page when a side nav is collapsible. Setting the width to 100% causes it to overflow the page due to the dynamic nature of the side nav. Using calc() isn&apos ...

The JavaScript code that added links to the mobile menu on smaller screens is no longer functioning properly

I recently created a website with a mobile navigation menu that should appear when the browser width is less than 1024px. However, I used some JavaScript (with jQuery) to include links to close the menu, but now the site is not displaying these links and t ...