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

React向Spring Boot传Multipart文件时415错误的解决方法

解决React + Spring Boot + axios图片上传问题

核心问题

你当前的前端代码直接将File对象作为请求体传给axios,这会导致请求的Content-Type不是后端期望的multipart/form-data,进而触发415或400错误。后端的@RequestParam("myImage")需要接收来自表单的文件字段,必须用FormData包装文件后再发送。

前端修复步骤

修改handleSubmit函数,将选中的图片包装到FormData中,axios会自动处理正确的请求头(包括multipart边界),不要手动设置Content-Type:

const [selectedImage, setSelectedImage] = useState(null);

function handleSubmit(){
    axios.defaults.withCredentials = true;
    // 创建FormData并添加文件,key需和后端@RequestParam的value一致
    const formData = new FormData();
    formData.append('myImage', selectedImage);
    
    axios.post('http://localhost:8080/api/image/', formData)
        .then(response => {
            if(response.status === 200){
                console.log(response.data);
                // window.location.href = "/user-dash"
            } else {
                console.log("请求未成功");
            }
        })
        .catch(error => console.error(error));
}

后端优化建议

  1. 调整数据库字段长度:你的ImageData类中imageData字段的@Column(length = 1000)限制了仅能存储1000字节的数据,绝大多数图片都会超过这个大小,导致上传失败或数据截断。建议移除长度限制:
@Lob
@Column(name = "imagedata")
private byte[] imageData;
  1. 确认跨域配置:如果前端和后端端口不同(比如前端3000,后端8080),需确保Spring Boot允许带凭证的跨域请求。可以在控制器类上添加:
@CrossOrigin(origins = "http://localhost:3000", allowCredentials = "true")

或者配置全局CORS规则。

验证步骤

  1. 重启前后端服务
  2. 选择图片并点击保存,检查前端控制台是否返回成功响应
  3. 查看数据库image_data表是否新增记录

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 20:24:51