React(Axios)向ASP.NET Core传输图片集合时请求读取失败问题
解决文件数组上传至ASP.NET Core Minimal API端点的问题
核心问题定位
客户端手动设置multipart/form-data请求头会丢失自动生成的boundary分隔符,导致服务器无法正确解析FormData;同时需确保前后端参数名完全匹配。
修复步骤
1. 客户端(React + Axios)修改
移除手动设置的Content-Type,Axios在接收FormData时会自动生成包含boundary的正确请求头,同时规范FormData的构造:
// 构造FormData const data = new FormData(); images.forEach((image) => { // 键名"images"需与服务器参数名一致,可选添加文件名 data.append("images", image, image.name); }); await Api.UploadImages(data); // Axios请求方法修改 static async UploadImages(images: FormData): Promise<AxiosResponse> { return axiosApi.post( "/images/images", images // 移除手动设置的headers,Axios自动处理multipart/form-data ); }
2. 服务器端(ASP.NET Core Minimal API)优化
使用IFormFileCollection接收文件集合,确保绑定源[FromForm]正确,若服务端需要List<IFormFile>可直接转换:
private static async Task<IResult> LoadImages( HttpContext context, IImageService imageService, [FromForm] IFormFileCollection images) { try { // 转换为List<IFormFile>适配服务层方法 return Results.Ok(await imageService.LoadImagesAsync(images.ToList())); } catch { return Results.BadRequest(new ErrorDto("An unexpected error occurred while loading the image.")); } }
3. 可选:调整上传文件大小限制
若上传大文件,需在Program.cs中配置FormOptions:
builder.Services.Configure<FormOptions>(options => { // 设置最大上传大小为10MB,按需调整 options.MultipartBodyLengthLimit = 10 * 1024 * 1024; });
排查验证点
- 确认前后端参数名均为
images,大小写敏感 - 检查请求路径与服务器路由匹配(用户标注路径正确可忽略)
- 确保服务器未启用干扰FormData解析的中间件
内容的提问来源于stack exchange,提问作者Cyril
相关产品推荐
相关产品推荐

