You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React提交带图片表单到ASP.NET接口存SQL Server varbinary字段报错求助

问题根源

你遇到的报错由三个核心错误共同导致:

  1. 前端上传的是图片预览用的blob:开头的URL字符串,不是真实的文件对象
  2. 后端使用[FromBody]注解接收参数,仅支持JSON/XML等结构化请求体,无法解析multipart/form-data格式的表单数据
  3. 手动设置multipart/form-data请求头会丢失请求必须的boundary分隔符,反而导致服务器无法解析表单内容

前端修改步骤

  1. 首先调整state结构,新增字段存储原始文件对象:
state = {
  file: null, // 保留该字段用于图片预览
  rawFile: null, // 新增字段存储原始文件对象用于上传
  name: "",
  phoneNumber: "",
  email: "",
  status: "Active",
  specialty: "",
  specialities: [],
};
  1. 修改handleFileChange方法,同时保存预览URL和原始文件:
handleFileChange = (event) => {
  const selectedFile = event.target.files[0];
  this.setState({
    file: URL.createObjectURL(selectedFile),
    rawFile: selectedFile
  });
};
  1. 调整handleSubmit中FormData的文件赋值逻辑:
// 把原来的DATA.doctorProfileImg替换为rawFile
formData.append("doctorProfileImg", this.state.rawFile);
  1. 移除所有手动设置multipart/form-data请求头的代码,fetch传递FormData时会自动生成带正确boundary的请求头。

后端修改步骤

  1. 调整TDoctor模型结构,新增IFormFile类型属性接收上传的文件,同时保留byte[]类型属性映射数据库的varbinary(max)字段:
public class TDoctor
{
    // 原有字段(DoctorId、DoctorName等)省略
    public IFormFile DoctorProfileImg { get; set; } // 接收前端传的文件
    public byte[] DoctorProfileImgBytes { get; set; } // 对应SQL Server的varbinary(max)字段
}
  1. 修改控制器方法的参数注解,同时新增文件转二进制的逻辑:
// 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 11:12:01