Search code examples
javascripthtmljsonformsmultipart

Multipart with additional json form


I have controller:

@RequestMapping(method = RequestMethod.POST)
@Consumes(MediaType.MULTIPART_FORM_DATA)
public String upload(
        @RequestPart(name="meta", required = false) String jsonMeta,
        @RequestPart(name="file") MultipartFile[] uploadingFiles) throws IOException { 
//...
MetaData metaData =  new ObjectMapper().readValue(meta, MetaData.class);
//... 
}

I need to create html form for that with several inputs for metadata and one for input for files.

It should create json from input fields, add it to multipart along with binary file and submit it.

I found a way to serialize full form to json, but couldn't get how to make it combine with file input in one form.


Solution

  • To combine, you have to use formdata in javascript. Syntax goes like this,

    var formData = new FormData();
    formData.append('meta', {key: 'value'});
    formData.append('file',  file);
    

    Now, pass the formData as a parameter to your POST request. Job Done!