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

Spring Boot文件上传报Unsupported Media Type(415)错误求助

问题根源分析

415错误的核心原因是Spring MVC与JAX-RS注解混用,导致请求处理逻辑冲突:你同时使用了Spring MVC的@Controller、@RequestParam,以及JAX-RS的@Path、@POST,两种框架的注解无法协同工作,最终导致请求媒体类型解析失败。

解决方案

方案1:改用纯Spring MVC实现(推荐)

统一使用Spring MVC的注解体系,适配Spring Boot的自动配置:

@RestController
@RequestMapping("/my")
public class MyResource {

    @PostMapping("parseFile")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "OK"),
            @ApiResponse(responseCode = "400", description = "Invalid format")})
    public ResponseEntity<?> parseFile(@RequestParam("file") MultipartFile file) {
        // 你的文件处理逻辑
        return ResponseEntity.ok().build();
    }
}
  • 移除@MultipartConfig:Spring Boot的自动配置已经覆盖了该注解的功能
  • 用@RestController替代@Controller(直接返回响应体,无需视图解析)
  • 用Spring MVC的@PostMapping、@RequestMapping替代JAX-RS的@POST、@Path

方案2:坚持使用JAX-RS(如Jersey)

如果项目依赖JAX-RS框架,需调整参数注解并引入multipart依赖:

@Path("/my")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.MULTIPART_FORM_DATA)
public class MyResource {

    @POST
    @Path("parseFile")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "OK"),
            @ApiResponse(responseCode = "400", description = "Invalid format")})
    public Response parseFile(@FormDataParam("file") InputStream fileInputStream,
                              @FormDataParam("file") FormDataContentDisposition fileMetaData) {
        // 你的文件处理逻辑
        return Response.ok().build();
    }
}
  • 添加Jersey multipart依赖到pom.xml:
<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-multipart</artifactId>
</dependency>

配置修正

  1. 删除手动创建MultipartAutoConfiguration的Bean:Spring Boot的自动配置已经足够,手动创建会导致配置冲突
  2. 调整application.yml的multipart参数(file-size-threshold不应大于max-file-size):
spring:
  servlet:
    multipart:
      enabled: true
      max-file-size: 2MB
      file-size-threshold: 1MB

Postman请求验证

  • 确保请求方法为POST,URL路径正确(如/my/parseFile,根据项目上下文路径调整)
  • Body选择form-data,Key设置为file,Type选择File并上传目标.ics文件
  • 不要手动设置Content-Type,Postman会自动生成multipart/form-data; boundary=xxx的正确请求头

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 09:25:19