向Spring Boot REST API发送FormData返回400错误该如何解决?
删除请求头中手动设置的
multipart/form-data配置
当你直接传递FormData对象作为请求体时,浏览器会自动生成包含boundary分隔符的正确multipart/form-data请求头,你手动设置该头字段时不会携带boundary参数,会导致Spring无法解析FormData结构,直接抛出400错误,这是这类问题最常见的诱因。校验DTO字段与FormData参数名匹配
你使用@ModelAttribute接收参数,需要确保UpdateProfilePictureDTO类中存在名为profile_picture的字段,且有对应的get/set方法。如果DTO字段用的是驼峰命名profilePicture,可以在字段上加上@RequestParam("profile_picture")注解强制绑定,或者把FormData里append的key改为和DTO字段名完全一致。检查文件对象有效性
确认newFileList[0]是合法的File对象,不存在undefined、null的情况,避免传递空参数导致后端绑定失败。调整Spring Boot文件上传配置
如果上传的图片体积超过Spring Boot默认的文件上传大小限制,也会触发400错误,可在application.yml中调整配置:spring: servlet: multipart: max-file-size: 20MB max-request-size: 20MB校验请求路径一致性
确认React侧的apiEndPoint拼接后完整路径和后端@RequestMapping配置的/v1/users/profile-picture/update完全一致,路径拼写错误也可能引发400类错误。
修正后的React请求示例
export async function profilePictureUpdate(formData) { const response = await http.post( apiEndPoint + '/profile-picture/update', formData, { headers: { Authorization: `Bearer ${getJwt()}` } }); console.log("response of profile picture", response); return response }
内容的提问来源于stack exchange,提问作者Prasad Darshana

