Hashan Mahesh
Hashan Mahesh

Reputation: 103

How to post an image placed inside a json object in reactjs to a spring boot back end rest api

I am creating a simple application which takes user details at the front end, and send them to the back end. Front end of the application is developed using ReactJs while the back end is totally spring boot. Here you can see the object which I am generating at the front end which then going to be sent to the back end.

    this.state = {
        user_details:{
            first_name: '',
            last_name: '',
            phone_number: '',
            email: '',
            password: '',
            birth_date: new Date(),
            nic: '',
            street_address: '',
            street_address2: '',
            city: '',
            state:'',
            zip_code: '',
            nationality: '',
            religion: '',
            photo: null
        }

As you can see above I am taking an image file from the user and then assign that image to the this.state.user_details.photo which is initially null.

As the user clicks the submit button in the reactJs form, the user_details object will be sent to the back end using the following axios call,

saveUserDetails(user_details){
    return axios.post("http://localhost:8080/teacher_details",user_details)
}

This request will be handled by the following PostMapping method which is defined at the back end

@PostMapping("/teacher_details")
public void saveTeacherDetails(@RequestBody UserDetails userDetails) {
    userRepo.save(userDetails);
    
}

The UserDetails class is the wrapper class which responsible to map the values in the request body to an object, here is the UserDetails class's member variables,

private String email;
private String nic;
private String firstName;
private String lastName;
private String phoneNumber;
private Date birthDate;
private String streetAddr1;
private String streedAddr2;
private String state;
private String city;
private String zipCode;
private String nationality;
private String religion;
private MultipartFile photo;

And I do have all the getters, setters, no args constructor, and the all args constructor But when I click the submit button at the front end, i get the following exception,

com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `org.springframework.web.multipart.MultipartFile` (no Creators, like default constructor, exist): abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information

I don't know what is happening here. All I want is to take the image along with the data and add them inside an ArrayList of UserDetails.

Am I doing a wrong thing here, or what is the error here. Can anyone explain me

Upvotes: 0

Views: 379

Answers (1)

Emmanuel Ogoma
Emmanuel Ogoma

Reputation: 582

change your json to formdata, below function will help

 createFormData(object, form, namespace) {
        const formData = form || new FormData();
        for (let property in object) {
            if (!object.hasOwnProperty(property) ||      !object[property]) {
                continue;
            }
            const formKey = namespace ? `${namespace}[${property}]` : property;
            if (object[property] instanceof Date) {
                formData.append(formKey, object[property].toISOString());
            } else if (typeof object[property] === 'object' && !(object[property] instanceof File)) {
                createFormData(object[property], formData, formKey);
            } else {
                formData.append(formKey, object[property]);
            }
        }
        return formData;
    }

and remove @RequestBody in the controller since we are not posting json now but a form data;

Now modify this method

saveUserDetails(user_details){
return axios.post("http://localhost:8080/teacher_details",user_details)
}

to

saveUserDetails(user_details){
let formData=createFormData(user_details);
return axios.post("http://localhost:8080/teacher_details",formData)
}

Upvotes: 1

Related Questions