Following the link provided by @Vishal Zanzrukia
I added this configuration:
import java.util.ArrayList;
import org.springframework.boot.info.BuildProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
@Configuration
public class OpenApiConfig {
/**
*
* This method is needed to allow sending multipart requests. For example, when an item is
* created together with an image. If this is not set the request will return an exception with:
*
* Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content-Type
* 'application/octet-stream' is not supported]
*
* @param converter
*/
public OpenApiConfig(MappingJackson2HttpMessageConverter converter) {
var supportedMediaTypes = new ArrayList<>(converter.getSupportedMediaTypes());
supportedMediaTypes.add(new MediaType("application", "octet-stream"));
converter.setSupportedMediaTypes(supportedMediaTypes);
}
...
And now it seems to be working as expected with a code like this:
Controller.java
@PostMapping(path = "/", consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Item> createItemWithoutImage(@Valid @RequestBody Item item) {
Item createdItem = itemService.createItem(item);
return ResponseEntity.status(HttpStatus.CREATED).body(createdItem);
}
@PostMapping(path = "/", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<Item> createItem(@Valid @RequestPart Item item,
@RequestPart(name = "image", required = false) MultipartFile imageFile) {
// DO Something with the image
Item createdItem = itemService.createItem(item);
return ResponseEntity.status(HttpStatus.CREATED).body(createdItem);
}
This is how it looks in swagger: