Search code examples
javascriptjavaspringmultipartform-dataform-data

Spring image, form values and list of objects in FormData


I have RestController endpoint:

Mono<A> editA(@PathVariable String id, @Valid A a)

Class A looks like that:

class A {
  private MultipartFile imageToSave;
  private String name;
  private String otherString;
  private ArrayList<B> bList;
}

Class B looks similar like class A (but contains just String fiels).

Frontend client(React using Axios) sends form values (two strings, image file). I use javascript FormData object to send this values into one request and it was working fine.

But i also want to send a list B object. So I tried just add a list B objects to FormData and send it.

How i can send list with object using FormData and them map it to ArrayList ?

Resolved [org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors Field error in object 'a' on field 'bList': rejected value [[object Object]]; codes [typeMismatch.a.bList,typeMismatch.bList,typeMismatch.java.util.ArrayList,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [a.bList,bList]; arguments []; default message [bList]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.ArrayList' for property 'bList'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'java.util.ArrayList' for property 'bList': no matching editors or conversion strategy found]]


Solution

  • I had a similar kind of error while passing error using formData in laravel. Turns out you cant use the formData API with the arrays. Have a look at the following url : https://developer.mozilla.org/en-US/docs/Web/API/FormData/append It only accepts string or blob. For your solution, you will have to something like what I did.

      let formData = {};
                for (var property in this.form) {
                    if (this.form.hasOwnProperty(property)) {
                          //  formData.append(property,this.form[property]);
                            formData[property] = this.form[property];
    
                    }
                }
    

    Here what I am doing is essentially just building object from the forms input properties and then using the below code passing through axios.

    axios({
                        method: 'post',
                        url: url
                        data : formData,
                        headers:{
                            'Content-Type': 'application/json',
                        }
                    }).then((response) => { ... });