将带有asp.net核心的文件作为字节数组上载到数据库中

时间:2017-07-05 16:37:25

标签: c# asp.net-core asp.net-core-mvc

我的代码:

    public class Employee
    {
        public int EmployeeId { get; set; }
        public string FullName { get; set; }
        public byte[] AvatarImage { get; set; }
    }

    public class EmployeeVm
    {
      public int EmployeeId { get; set; }
      public string FullName { get; set; }
      public IFormFile AvatarImage { get; set; }
    }


    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create(EmployeeVm model)
    {
        if (ModelState.IsValid)
        {
            var employees = new Employee
            {
               FullName  = model.FullName
            };
            using (var memoryStream = new MemoryStream())
            {
                employees.AvatarImage = memoryStream.ToArray();
                await model.AvatarImage.CopyToAsync(memoryStream);

            }
            _context.Add(employees);
               await _context.SaveChangesAsync();
            return RedirectToAction("Index");
        }
        return View(model);
    }

我得到的只是

  

nullReferenceException:未将对象引用设置为对象的实例。 await model.AvatarImage.CopyToAsync(memoryStream);

我是asp.net核心的新手,我不明白asp.net核心如何处理MemoryStream

1 个答案:

答案 0 :(得分:2)

您必须先将IFormFile内容存储到内存流中。内存流对象为空,因此调用它memoryStream.ToArray()会带来null值。在调用上述方法之前,首先将上传的头像分配给它。

using (var memoryStream = new MemoryStream())
{
     await model.AvatarImage.CopyToAsync(memoryStream);
     employees.AvatarImage = memoryStream.ToArray();

}