Axios提交含文件的Actor列表请求后SpringBoot端Actors列表为空
解决方案
1. 前端按Spring解析规则手动构建FormData
因为请求包含MultipartFile类型的文件,axios会自动将请求转为multipart/form-data格式,但直接传递对象数组时,FormData无法正确序列化数组结构,导致后端无法解析。需要手动遍历数组,按actors[索引].字段名的格式添加到FormData中:
const formData = new FormData(); // 添加基础字段 formData.append('title', titleRef.current.value); formData.append('movie', movieFileRef.current.files[0]); formData.append('poster', posterFileRef.current.files[0]); formData.append('genre', genreRef.current.value); formData.append('rating', ratingRef.current.value); formData.append('yearOfRelease', yearRef.current.value); formData.append('country', countryRef.current.value); // 添加director嵌套字段 formData.append('director.firstName', directorFirstNameRef.current.value); formData.append('director.lastName', directorLastNameRef.current.value); formData.append('director.patronymic', directorPatronymicRef.current.value); formData.append('director.age', directorYearRef.current.value); // 添加actors数组,按索引逐个添加字段 const actors = [actorForm, actorForm, actorForm, actorForm]; actors.forEach((actor, index) => { formData.append(`actors[${index}].firstName`, actor.firstName); formData.append(`actors[${index}].lastName`, actor.lastName); formData.append(`actors[${index}].patronymic`, actor.patronymic); formData.append(`actors[${index}].age`, actor.age); formData.append(`actors[${index}].gender`, actor.gender); }); formData.append('plotDescription', plotDescriptionRef.current.value); // 发送请求,无需手动设置Content-Type,axios会自动处理 axios.post(urlServer.URL_MOVIE_SAVE, formData);
2. 确认后端实体类配置正确
- 确保
AddMovieForm中的actors字段为List<ActorForm>类型,且通过@Data注解生成了正确的getter/setter(当前代码已满足)。 - 实体类的字段名(如
firstName)需和前端FormData中的键名完全匹配,大小写一致。
3. 避免手动设置请求头
不要手动指定Content-Type: multipart/form-data,axios在发送FormData时会自动生成包含boundary的正确请求头,手动设置会导致boundary缺失,后端无法解析请求内容。
内容的提问来源于stack exchange,提问作者Arturo Gatti
相关产品推荐
相关产品推荐

