Spring Boot-多部分-不支持的媒体类型

时间:2019-02-07 14:45:18

标签: java rest spring-boot

我想在一个帖子请求中发送一个文件和一个json模型。

我的请求映射如下:

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

我收到的错误:

{
    "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"
}

邮递员要求: http://imgshare.free.fr/uploads/62f4cbf671.jpg

我的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 个答案:

答案 0 :(得分:1)

您可以尝试使用它代替

@RequestPart("file") MultipartFile file

使用此

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

并确保将请求类型设置为multipart / form-data 您可以从邮递员的标题标签中进行设置。

postman example

如果需要使用多部分文件发送另一个对象,则可以将其作为字符串发送,然后可以将其转换为后端的对象。

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

邮递员请求示例:

enter image description here