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

SpringBoot对接Fetch时出现无效MIME类型undefined报错求助

解决Fetch发送FormData时SpringBoot报HttpMediaTypeNotSupportedException的问题

我之前也踩过这个坑!其实你前端设置Content-Type: undefined让浏览器自动处理的思路是完全正确的,问题大概率出在前后端参数解析的匹配逻辑上,咱们一步步排查解决:

1. 后端接口必须用@RequestPart替代@RequestParam

SpringBoot里,@RequestParam只适合解析multipart里的简单字符串或文件,而你要同时传递文件和JSON对象,得用@RequestPart来分别绑定不同类型的请求部分。示例代码如下:

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class UploadController {

    @PostMapping("/api/upload")
    public String handleUpload(
            @RequestPart("file") MultipartFile file,
            @RequestPart("data") YourCustomDto data // 直接绑定你对应的JSON实体类
    ) {
        // 处理文件和业务数据的逻辑
        return "Upload success";
    }
}

2. 前端FormData的JSON字段必须正确格式化

别直接把JSON对象append到FormData里!浏览器会把它转成[object Object]字符串,后端根本无法解析成JSON对象。你需要把JSON转成字符串,并且指定它的Content-Type为application/json:

const formData = new FormData();
// 添加文件
formData.append('file', document.getElementById('fileInput').files[0]);
// 添加JSON数据:转成字符串并指定类型
const jsonData = { name: "test", age: 25 };
formData.append('data', JSON.stringify(jsonData), {
    type: 'application/json'
});

// 发送请求:不要手动设置Content-Type,浏览器会自动添加正确的multipart/form-data和分隔符
fetch('/api/upload', {
    method: 'POST',
    body: formData
})
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.error('Error:', error));

3. 检查SpringBoot的Multipart配置是否正常

确保你的项目已经引入了spring-boot-starter-web依赖(它默认包含了multipart解析的自动配置),如果有自定义配置,不要禁用multipart或者设置错误的参数:

# application.yml 示例配置
spring:
  servlet:
    multipart:
      enabled: true # 必须开启multipart支持
      max-file-size: 10MB # 根据业务需求调整文件大小限制
      max-request-size: 10MB

4. 查看异常详情定位具体问题

如果还是报错,一定要看后端日志里的完整异常信息,比如它会提示Content type 'text/plain' not supported——这说明前端的JSON字段没指定application/json类型,后端无法解析;或者提示某个DTO字段不匹配,这时候要检查你的实体类是否和前端JSON结构完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:48:42