user3525152
user3525152

Reputation: 21

Uploading files with asp.net core into database as byte array

My code:

    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);
    }

All i got was

nullReferenceException: Object reference not set to an instance of an object. await model.AvatarImage.CopyToAsync(memoryStream);

I'm new to asp.net core, I don't understand how asp.net core handles MemoryStream.

Upvotes: 2

Views: 8950

Answers (1)

Tonto
Tonto

Reputation: 3102

You have to store IFormFile content to the memorystream before. The memory stream object is empty so calling it memoryStream.ToArray() is what brings the null value. Assign the uploaded avatar to it first before calling the method above.

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

}

Upvotes: 9

Related Questions