繁体   English   中英

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

[英]Spring Boot - Multipart - Unsupported Media Type

我想在一个帖子请求中发送一个文件和一个 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

我的网络配置:

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

    }

你可以尝试使用而不是这个

@RequestPart("file") MultipartFile file

用这个

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

并确保将请求类型设置为 multipart/form-data 您可以在 headers 选项卡中从邮递员那里设置它。

邮递员例子

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

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

邮递员请求示例:

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM