Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot - Multipart - Unsupported Media Type

I want to send a file and a json model at one post request.

My Request Mapping looks like that:

    @PostMapping("{id}/files")
    public MyOutput create(@PathVariable String id, @RequestPart("request") MyInput input, @RequestPart("file") MultipartFile file) {
    // ...
    }

The error I receive:

{
    "timestamp": "Feb 7, 2019, 3:18:50 PM",
    "status": 415,
    "error": "Unsupported Media Type",
    "message": "Content type 'application/octet-stream' not supported",
    "trace": "org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/octet-stream' not supported...,
    "path": "/tests/12345/files"
}

Postman request: http://imgshare.free.fr/uploads/62f4cbf671.jpg

My WebConfig:

    @Override
    public void configureMessageConverters(final List<HttpMessageConverter<?>> converters) {

        GsonBuilder builder = new GsonBuilder();
        Gson gson = builder.setPrettyPrinting().create();

        final GsonHttpMessageConverter msgConverter = new GsonHttpMessageConverter();
        msgConverter.setGson(gson);
        msgConverter.setDefaultCharset(StandardCharsets.UTF_8);
        converters.add(msgConverter);

        converters.add(new StringHttpMessageConverter());

        //
        converters.add(new ByteArrayHttpMessageConverter());
        converters.add(new FormHttpMessageConverter());
        converters.add(new ResourceHttpMessageConverter());

    }
like image 547
fuerteVentura22 Avatar asked Mar 05 '23 13:03

fuerteVentura22


1 Answers

You can try to use instead of this

@RequestPart("file") MultipartFile file

use this

@RequestParam(value = "file",required = false) MultipartFile file

And be sure you set the request type as multipart/form-data You can set it from postman in the headers tab.

postman example

If another object you need to send with multipart file,you can send it as a string and then you can convert it to object at the backend side.

  @PostMapping("/upload")
    public void uploadFile(@Nullable @RequestParam(value = "file",required = false) MultipartFile file,
                                            @RequestParam(value = "input", required = false) String st)
    {
        ObjectMapper om = new ObjectMapper();
        MyInput input = null;
        try {
            input = om.readValue(st, MyInput.class);   //string st -> MyInput input
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Postman request example :

enter image description here

like image 152
Cocuthemyth Avatar answered Mar 26 '23 23:03

Cocuthemyth