Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Introduction

In this tutorial, we’ll focus on various mechanisms for sending multipart requests in Spring Boot. Multipart requests consist of sending data of many different types separated by a boundary as part of a single HTTP method call.

Generally, we can send complicated JSON, XML, or CSV data, as well as transfer multipart file(s) in this request. Examples of multipart files include audio or image files. Furthermore, we can send simple key/value pair data with the multipart file(s) as a multipart request.

Now let’s look into the various ways we can send this data.

2. Using @ModelAttribute

Let’s consider a simple use case of sending an employee’s data consisting of a name and file using a form.

First, we’ll create an Employee abstraction to store the form data:

public class Employee {
    private String name;
    private MultipartFile document;
}

Then we’ll generate the form using Thymeleaf:

<form action="#" th:action="@{/employee}" th:object="${employee}" method="post" enctype="multipart/form-data">
    <p>name: <input type="text" th:field="*{name}" /></p>
    <p>document:<input type="file" th:field="*{document}" multiple="multiple"/>
    <input type="submit" value="upload" />
    <input type="reset" value="Reset" /></p>
</form>

The important thing to note is that we declare the enctype as multipart/form-data in the view.

Finally, we’ll create a method that accepts the form data, including the multipart file:

@PostMapping(path = "/employee", consumes = { MediaType.MULTIPART_FORM_DATA_VALUE })
public String saveEmployee(@ModelAttribute Employee employee) {
    employeeService.save(employee);
    return "employee/success";
}

Here, the two particularly important details are:

  • consumes attribute value is set to multipart/form-data
  • @ModelAttribute has captured all the form data into the Employee POJO, including the uploaded file

3. Using @RequestPart

This annotation associates a part of a multipart request with the method argument, which is useful for sending complex multi-attribute data as payload, e.g., JSON or XML.

Let’s create a method with two arguments, first of type Employee and second as MultipartFile. Furthermore, we’ll annotate both of these arguments with @RequestPart:

@PostMapping(path = "/requestpart/employee", consumes = { MediaType.MULTIPART_FORM_DATA_VALUE })
public ResponseEntity<Object> saveEmployee(@RequestPart Employee employee, @RequestPart MultipartFile document) {
    employee.setDocument(document);
    employeeService.save(employee);
    return ResponseEntity.ok().build();
}

Now, to see this annotation in action, we’ll create the test using MockMultipartFile:

@Test
public void givenEmployeeJsonAndMultipartFile_whenPostWithRequestPart_thenReturnsOK() throws Exception {
    MockMultipartFile employeeJson = new MockMultipartFile("employee", null,
      "application/json", "{\"name\": \"Emp Name\"}".getBytes());

    mockMvc.perform(multipart("/requestpart/employee")
      .file(A_FILE)
      .file(employeeJson))
      .andExpect(status().isOk());
}

The important thing to note above is that we’ve set the content type of the Employee part as application/JSON. We’re also sending this data as a JSON file in addition to the multipart file.

Further details on how to test multipart requests can be found here.

4. Using @RequestParam

Another way of sending multipart data is to use @RequestParam. This is especially useful for simple data, which is sent as key/value pairs along with the file:

@RequestMapping(path = "/requestparam/employee", method = POST, consumes = { MediaType.MULTIPART_FORM_DATA_VALUE })
public ResponseEntity<Object> saveEmployee(@RequestParam String name, @RequestPart MultipartFile document) {
    Employee employee = new Employee(name, document);
    employeeService.save(employee);
    return ResponseEntity.ok().build();
}

Let’s write the test for this method to demonstrate:

@Test
public void givenRequestPartAndRequestParam_whenPost_thenReturns200OK() throws Exception {
    mockMvc.perform(multipart("/requestparam/employee")
      .file(A_FILE)
      .param("name", "testname"))
      .andExpect(status().isOk());
}

5. Conclusion

In this article, we learned how to effectively handle multipart requests in Spring Boot.

Initially, we sent multipart form data using a model attribute. Then we looked at how to separately receive multipart data using the @RequestPart and @RequestParam annotations.

As always, the full source code is available over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are closed on this article!