1

While sending data from javascript using formdata values are not mapping properly

I have to send a file and a list of phonesNumbers

javascript file

let fdata = new FormData();
fdata.append("postalCode", $("#c-postalCode").val());
fdata.append("dob", $("#c-dob").val());
fdata.append("contactImage", $("#c-contactimg")[0].files[0]);

fdata.append("phoneNos", [{id:"1",phoneNo:"12345"}]);

fetch("/cm/save/contact/details", {
body: fdata,
method: "POST"
}).then((response) => { //Somecode})

RestController class

In method using ModelAttribute to map data coming from javascript

@PostMapping("/save/contact/details")
    public void saveContactDetails(@ModelAttribute ContactDetailsDto contactDetailsDto) {
        System.out.println(contactDetailsDto);
    }

ContactDetailsDto.java

@Data
@NoArgsConstructor
@AllArgsConstructor
public class ContactDetailsDto {

    //Somecode

    private MultipartFile contactImage;

    @NotBlank
    private List<PhoneNumberDto> phoneNos = new ArrayList<>();

}

PhoneNumberDto.java

@Data
@NoArgsConstructor
@AllArgsConstructor
public class PhoneNumberDto {

    private Integer id;
    private String phoneNo;

    public PhoneNumberDto(String phoneNo) {
        super();
        this.phoneNo = phoneNo;
    }

}

But when printing data id filed is null and phoneNo is showing object

ContactDetailsDto(id=null, name=asd, email=, contactImage=org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile@2dc05cd7, address1=, address2=, postalCode=null, country=101, state=4030, city=57709, dob=null, phoneNos=[PhoneNumberDto(id=null, phoneNo=[object Object])])

I have tried several things like creating different parametrized constructors, and sending different types/forms of data from javascript

How to exactly map data with fields with nested POJO class in it

1 Answers1

0

Take a look at FormData#append documentation

This right here, describes the second argument:

The field's value. This can be a string or Blob (including subclasses such as File). If none of these are specified the value is converted to a string.

Which means that you're not setting the FormData correctly - it doesn't allow passing an array or complex objects as a value.

Someone has already described a solution to this problem in this answer.

Kamil Bęben
  • 1,064
  • 8
  • 12