使用原生JavaScript和Spring Boot批量传图遇400错误求助
解决Spring Boot多文件上传时"the request part 'files' is not present"错误
问题根源
你前端代码中直接将文件数组整体添加到FormData的方式错误:
pictureFormData.append('files', files) // 错误:直接传数组,后端无法解析
后端期望的是多个同名的files参数,每个对应一个文件,而不是一个包含数组的参数。
修正后的前端代码
遍历文件数组,逐个添加到FormData中:
// 遍历文件数组,逐个append files.forEach(file => { pictureFormData.append('files', file); }); pictureFormData.append('propCode', newProperty.propCode); await fetch("http://localhost:8083/property/upload", { method: "POST", body: pictureFormData }) .then((response) => { return response.text(); // 需return才能获取返回内容 }) .then(data => { console.log(data); // 处理返回结果 }) .catch((error) => console.error(error));
后端补充说明
- 你的后端代码使用
@RequestParam MultipartFile[] files是正确的,无需更换为@RequestPart(@RequestPart也可工作,但@RequestParam更适配该表单参数场景)。 - Spring Boot 2.x及以上版本默认已自动配置multipart支持,无需额外添加
MultipartResolverBean,有自定义需求时再调整配置。
内容的提问来源于stack exchange,提问作者Joel Garcia
相关产品推荐
相关产品推荐

