"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

Creating a fresh shortcut on the selenium IDE

Is there a way to customize shortcuts in Selenium IDE by modifying its code? For instance, I would like to set the shortcut ctrl + p for the action run test case, similar to how the save action is assigned ctrl + s. I've searched for the JavaScript ...

Error: AngularJS is experiencing an injector module error that has not been caught

I have set up an Angular boilerplate that includes various elements such as meta tags, CDN links, and script tags. However, I am encountering a persistent error in my console and cannot figure out the root cause of it. https://i.stack.imgur.com/qPGby.png ...

Error: The value of _This.props is not defined

Hey there, I am new to working with React Native and could really use some assistance with this issue: TypeError: _props.goToScreen is not a function. Any help would be greatly appreciated, thank you in advance! In my Profile.js file, I am trying to click ...

Is it possible to pass multiple API props to a NextJs Page at once?

I am currently facing a challenge in rendering a page that requires data from two different API fetches. The URL in the address bar appears as: http://localhost:3000/startpage?id=1 Below is the code snippet for the first API fetch: import { useRouter } f ...

When setting an attribute on load, Javascript may not properly apply the change to the attribute

I designed a webpage where images have a fade-in effect using a CSS class. Initially, 4 images load with the desired effect. However, I encounter an issue when trying to apply the same effect to a new image that appears upon clicking a button. Below is th ...

You have exceeded the maximum number of Facebook application requests allowed (#4)

My goal is to create a dynamic "social wall" on a website by pulling posts from a specific Facebook page using the Facebook API. Instead of utilizing any Facebook SDK, I am making cURL calls with the URLs directly. To fetch the posts, I rely on Javascript ...

SQL inputs with information that updates automatically / autofill SQL input boxes

Is it feasible to create a webpage that can connect to an SQL database, retrieve information from a table, and display it in a text box based on the input provided in another text box? Essentially, I am looking for a way to enable autofill functionality. I ...

Add value to a progress bar over time until it reaches the designated timeout

I'm struggling to implement a loading bar with a fixed timeout requirement. The goal is for the bar to be completely filled within 5 seconds. While I have successfully created the HTML and CSS components, I am facing difficulty in developing the JavaS ...

What can be done to stop $.ajax from automatically appending [] to my key names when making requests (aside from using processData: false

When attempting to utilize $.ajax for a POST request with data in the following format: { list: ["fake_id_0"], mapType: "fakeToRealId" } jQuery seems to alter the structure by adding brackets only to the key list, transforming it into: { lis ...

AngularJS stores AJAX data in a service for easy access

My scenario is quite simple: https://i.stack.imgur.com/Vmxqu.jpg The app begins at the Main View (/main), then the user clicks on the button in the top right corner to go to the Sub View (/sub). Upon launching the app with app.run(), the user's pro ...

Accessing information from MySQL using JSONArray and PDO!

After researching on the Internet, I discovered that many people recommend switching from the old mysql (and mysqli) extensions to PDO. Although I am new to PDO, I have learned some basics about it. However, when trying to solve my issue by searching thro ...

Comparing JSON in Clojure

During my testing, I have been comparing JSON results from various HTTP calls. However, I realized that simply comparing strings is too simplistic and unreliable, especially if the order of elements changes. Can you suggest a better way to compare two JSON ...

Image capture by automation

I'm in the midst of a project automating tasks, where I have designed a basic program to generate testing reports and capture screenshots. package ReportTest; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; im ...

Update the variable values in the Onclick function

I am trying to modify the onClick function attached to a button. My goal is to change the function var from 'create' to 'update' when the page loads and also through other functions. I attempted the code below but it did not work as exp ...

Error: 'window not defined' or 'document not defined' encountered while importing a module in Next.js

I'm working on integrating a Wysiwyg editor into my web application. However, I encountered an error when trying to import the editor module. I tried using both react-draft-wysiwyg and react-quill. The former resulted in a "window not defined" error, ...

Load select box with options upon document load

After the document loads, I want to populate a select box with values from my database using ajax and jQuery. Can someone help me identify what's wrong with my code? <select class="form-control sec" id="sec" name="sec"> <option value="s ...

How can parameters be sent without using the .jshintrc file with the gulp-jshint package?

Currently in the process of transitioning a grunt project to a gulp project. In the existing gruntfile, there is a section for the jshint task that looks like this: jshint: { options: { trailing:true, evil:false, indent:4, ...

Using Jquery to Redirect Users According to URL Position

My current dilemma involves... I want to create a condition where if the URL specifically contains /foldername/index.htm or /foldername/ on mydomain.com, then it should redirect to http://www.example.com If the URL includes any URL parameter with /folder ...

A guide on how to efficiently update and submit a reactive form with a single click of the submit button in Angular

Currently, I have a view component setup where clicking the edit button directs me to the register component for form updates using patchvalue. The issue that I am facing is that when I update and register the form using the same button, it creates anothe ...

Exploring the comparison of information across two sets of databases using Node.js and MongoDB

In the realm of Node.js and MongoDB, I have set up two databases (1-btech2014 & 2-btechre2014) on a single server. My objective is to compare the data in btech2014 with that in btechre2014. If they match, I should retrieve the data from btech2014 as outpu ...