Spring Boot:发送multipart/form-data为何报415不支持媒体类型错误?
解决Spring Boot接口415 Unsupported Media Type错误(接收multipart/form-data)
可能的原因及解决方法
1. 显式指定接口支持的媒体类型
在@PostMapping中添加consumes属性,明确告知Spring MVC该接口处理multipart/form-data类型请求:
@PostMapping(value = "/posts", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public ResponseEntity<Post> createPost( @RequestPart(value = "text") String text, @RequestPart(value = "image", required = false) MultipartFile image, @RequestPart(value ="userId") Long userId ) { // 原有业务代码 }
2. 修正Postman请求配置
- 不要手动设置Content-Type:当选择form-data格式时,Postman会自动生成带
boundary的Content-Type头,手动输入multipart/form-data会丢失关键的boundary信息,导致Spring无法解析请求。 - 核对参数名:确保form-data中的参数名(
text、image、userId)与控制器注解中的value完全一致,注意大小写敏感。 - userId参数格式:直接输入数字(如
1),不要加引号,确保Spring能自动转换为Long类型。
3. 确认Multipart自动配置生效
Spring Boot默认已开启Multipart支持,若有自定义配置,检查application.properties/application.yml确保以下配置正确:
# 无需额外添加,若存在则确认值合理 spring.servlet.multipart.enabled=true spring.servlet.multipart.max-file-size=10MB spring.servlet.multipart.max-request-size=10MB
4. 改用@RequestParam接收简单类型参数
form-data中的简单类型(Long、String)用@RequestParam更适配,避免@RequestPart可能的类型转换问题:
@PostMapping(value = "/posts", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public ResponseEntity<Post> createPost( @RequestParam(value = "text") String text, @RequestParam(value = "image", required = false) MultipartFile image, @RequestParam(value ="userId") Long userId ) { // 原有业务代码 }
5. 完善服务层的文件转换逻辑
在postService.createPost(postDTO)中,需要将MultipartFile转为byte[]后存入实体:
public Post createPost(PostDTO postDTO) { Post post = new Post(); post.setText(postDTO.getText()); post.setUserId(postDTO.getUserId()); if (postDTO.getImage() != null) { try { post.setImage(postDTO.getImage().getBytes()); } catch (IOException e) { throw new RuntimeException("图片转字节数组失败", e); } } return postRepository.save(post); }
测试验证
修改后重启应用,用Postman重新测试:
- 选择POST方法,输入接口URL
- 切换到Body标签,选择form-data格式
- 添加参数:text(Text类型,输入内容)、image(File类型,可选上传文件)、userId(Text类型,输入数字)
- 直接发送请求,无需手动配置Headers中的Content-Type
内容的提问来源于stack exchange,提问作者Subham Surmara
相关产品推荐
相关产品推荐

