React提交带图片表单到ASP.NET接口存SQL Server varbinary字段报错求助
问题根源
你遇到的报错由三个核心错误共同导致:
- 前端上传的是图片预览用的
blob:开头的URL字符串,不是真实的文件对象 - 后端使用
[FromBody]注解接收参数,仅支持JSON/XML等结构化请求体,无法解析multipart/form-data格式的表单数据 - 手动设置
multipart/form-data请求头会丢失请求必须的boundary分隔符,反而导致服务器无法解析表单内容
前端修改步骤
- 首先调整state结构,新增字段存储原始文件对象:
state = { file: null, // 保留该字段用于图片预览 rawFile: null, // 新增字段存储原始文件对象用于上传 name: "", phoneNumber: "", email: "", status: "Active", specialty: "", specialities: [], };
- 修改
handleFileChange方法,同时保存预览URL和原始文件:
handleFileChange = (event) => { const selectedFile = event.target.files[0]; this.setState({ file: URL.createObjectURL(selectedFile), rawFile: selectedFile }); };
- 调整
handleSubmit中FormData的文件赋值逻辑:
// 把原来的DATA.doctorProfileImg替换为rawFile formData.append("doctorProfileImg", this.state.rawFile);
- 移除所有手动设置
multipart/form-data请求头的代码,fetch传递FormData时会自动生成带正确boundary的请求头。
后端修改步骤
- 调整
TDoctor模型结构,新增IFormFile类型属性接收上传的文件,同时保留byte[]类型属性映射数据库的varbinary(max)字段:
public class TDoctor { // 原有字段(DoctorId、DoctorName等)省略 public IFormFile DoctorProfileImg { get; set; } // 接收前端传的文件 public byte[] DoctorProfileImgBytes { get; set; } // 对应SQL Server的varbinary(max)字段 }
- 修改控制器方法的参数注解,同时新增文件转二进制的逻辑:
// POST: api/TDoctors [HttpPost] public async Task<IActionResult> PostTDoctor([FromForm] TDoctor tDoctor) { if (!ModelState.IsValid) { return BadRequest(ModelState); } // 将上传的文件转成字节数组存入数据库对应字段 if (tDoctor.DoctorProfileImg != null) { using var memoryStream = new MemoryStream(); await tDoctor.DoctorProfileImg.CopyToAsync(memoryStream); tDoctor.DoctorProfileImgBytes = memoryStream.ToArray(); } _context.TDoctor.Add(tDoctor); await _context.SaveChangesAsync(); return CreatedAtAction("GetTDoctor", new { id = tDoctor.DoctorId }, tDoctor); }
内容的提问来源于stack exchange,提问作者DarkVaderM
相关产品推荐
相关产品推荐

