You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot接收图片报415 Unsupported Media Type问题求助

解决Spring Boot接收MultipartFile时的415 Unsupported Media Type错误

问题原因

你遇到的415错误核心是请求格式与接口接收逻辑不匹配:

  • @RequestBody注解专门用于解析JSON/XML格式的请求体,但你通过Postman发送的是multipart/form-data类型的文件上传请求,Spring无法将分块的Multipart请求转换为ImageOpenLayer对象。
  • 即使你把consumes设为MediaType.ALL_VALUE,@RequestBody的解析规则也不支持Multipart请求的解析逻辑。

解决方案

1. 修改控制器方法的参数接收方式

去掉@RequestBody,改用@RequestPart直接接收MultipartFile,同时明确指定consumes为multipart/form-data:

@ApiOperation(value = "/getImage")
@RequestMapping(value = "getImage", method = RequestMethod.POST, 
                produces = MediaType.IMAGE_PNG_VALUE, 
                consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<Resource> getImage(@RequestPart("file") MultipartFile file) throws IOException {
    // 将MultipartFile封装到业务对象中
    ImageOpenLayer imageOpenLayer = new ImageOpenLayer();
    imageOpenLayer.setFile(file);
    this.servicio.getImage(imageOpenLayer);

    InputStream in = new BufferedInputStream(new FileInputStream(new File("MicrosoftTeams-image.png")));
    InputStreamResource fileResource = new InputStreamResource(in);
    return ResponseEntity
            .ok()
            .contentType(MediaType.IMAGE_PNG)
            .body(fileResource);
}

如果坚持要通过ImageOpenLayer对象接收,也可以使用@ModelAttribute(需确保对象内的字段都能通过form-data参数映射):

public ResponseEntity<Resource> getImage(@ModelAttribute ImageOpenLayer imageOpenLayer) throws IOException {
    // 业务逻辑不变
}

2. 调整Postman请求配置

保持使用form-data格式发送请求:

  • 在"Body"标签下选择form-data
  • 添加键值对,Key设为file(需和代码中@RequestPart的参数名一致)
  • 右侧类型选择File,然后选择本地图片文件发送

为什么改为String类型可以正常工作?

当你把file字段改为String时,Postman发送的是JSON格式请求(图片被转为Base64字符串放入JSON中),此时@RequestBody可以正常解析JSON为ImageOpenLayer对象,这是另一种文件上传方式,但会增加数据体积,对于图片这类二进制文件,更推荐使用multipart/form-data的方式。

内容的提问来源于stack exchange,提问作者Alejandro Gonzalez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 22:10:28