Spring MVC rest service with multipart request plus json

In spring we can expose rest service which accepts multipart request with json content.Below is rest service construction and java script code to hit such service.

Multipart Request with JSON Data  (also called Mixed Multipart) :

Based on RESTful service in Spring 4.0.2 Release, HTTP request with a First part with XML or JSON formatted data and a second part with a file can be achieved with @RequestPart .Below is the sample implementation.

Java Snippet:

Controller will have mixed @RequestPart and MultipartFile to serve such Multipart + JSON request.

@RequestMapping(value = "/executesampleservice", method = RequestMethod.POST, consumes = {"multipart/form-data"})
public boolean executeSampleService(@RequestPart("properties") @Valid ConnectionProperties properties, @RequestPart("file") @Valid @NotNull @NotBlank MultipartFile file) {
   return projectService.executeSampleService(project, file);

Java Script Implementation steps:

1. Create a FormData object.

2. Append the file to the FormData object using one of the below steps.
i. If the file has been uploaded using an input element of type "file", then append it to the FormData   object.
formData.append("file", document.forms[formName].file.files[0]);
ii. Directly append the file to the FormData object.
formData.append("file", myFile, "myfile.txt"); OR  formData.append("file", myBob, "myfile.txt");

3. Create a blob with the stringified JSON data and append it to the FormData object. This causes the Content-type of the second part in the multipart request to be "application/json" instead of the file type.
4. Send the request to the server.
5. Request Details :
    i. Content-Type : undefined
This causes the browser to set the Content-Type to multipart/form-data and fill the boundary correctly. Manually setting Content-Type to multipart/form-data will fail to fill in the boundary parameter of the request.

Javascript snippet:

 formData = new FormData();
    formData.append("file", document.forms[formName].file.files[0]);
    formData.append('properties', new Blob([JSON.stringify({
                    "name": "root",
                    "password": "root"                
                })], {
                    type: "application/json"


Request Details:

    method: "POST",
    headers: {
             "Content-Type": undefined
    data: formData

Request Payload:

  Accept:application/json, text/plain, */*
    Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryEBoJzS3HQ4PgE1QB
    Content-Disposition: form-data; name="file"; filename="myfile.txt"
    Content-Type: application/txt
    Content-Disposition: form-data; name="properties"; filename="blob"
    Content-Type: application/json


Show Comments: OR