I have a standard Controller method to respond to POST requests in the /products
route:
@PostMapping(value = "/products")
public ResponseEntity<ResponseMessage> postProduct(@RequestBody ProductUpsertRequestBody postRequest)
{
.
.
.
ProductUpsertRequestBody
is just a simple class that I use to capture the JSON payload:
public class ProductUpsertRequestBody implements Serializable
{
@JsonProperty("id") private String clientProductId;
@JsonProperty("product_name") private String productName;
@JsonProperty("product_type") private String productType;
@JsonProperty("cost_in_cents") private Long costInCents;
@JsonProperty("description") private String description;
@JsonProperty("label_color") private String labelColor;
.
.
.
I need to expand my controller method with a MultiPartFile
argument, transforming it into:
@PostMapping(value = "/products")
public ResponseEntity<ResponseMessage> postProduct(@RequestBody ProductUpsertRequestBody postRequest, @RequestParam MultiPartFile myImage)
{
.
.
.
But I'm confused as to how this controller method will even be called. It's not hard to make a rudimentary frontend with an HTML form that uploads as many images as I like, but then I lose the capacity to send a JSON payload (it's a REST API, and I'm sending it requests through Swagger 2.9, Postman, effectively curl
calls). How can I combine binary image uploading with a JSON payload, such that my controller can capture it? Perhaps exactly as importantly, is there a way for me to do this via Swagger or Postman, so that I can do end-to-end testing of my API?
Thats why you have multi part requests, the idea is you send multiple independant parts, each with their own content type.
Spring boot supports out of the box such cases. Here goes an example:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
@RestController
@RequestMapping(path = "/multi")
public class MultipartController {
private static final Logger LOG = LoggerFactory.getLogger(MultipartController.class);
@PostMapping
public void upload(@RequestPart(name = "user") User user,
@RequestPart(name = "my-file") MultipartFile file) {
LOG.info("User name: {}", user.getName());
LOG.info("File size: {}", file.getSize());
}
}
To test this you can use postman which also comes with support for this kind of requests