Spring Boot - Multipart - Unsupported Media Type

2019-08-01 09:18发布

问题:

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());

    }

回答1:

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.

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 :