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)); }
后端优化建议
- 调整数据库字段长度:你的
ImageData类中imageData字段的@Column(length = 1000)限制了仅能存储1000字节的数据,绝大多数图片都会超过这个大小,导致上传失败或数据截断。建议移除长度限制:
@Lob @Column(name = "imagedata") private byte[] imageData;
- 确认跨域配置:如果前端和后端端口不同(比如前端3000,后端8080),需确保Spring Boot允许带凭证的跨域请求。可以在控制器类上添加:
@CrossOrigin(origins = "http://localhost:3000", allowCredentials = "true")
或者配置全局CORS规则。
验证步骤
- 重启前后端服务
- 选择图片并点击保存,检查前端控制台是否返回成功响应
- 查看数据库
image_data表是否新增记录
内容的提问来源于stack exchange,提问作者BDorries
相关产品推荐
相关产品推荐

