Save photo in MVC

1

I'm trying to save a photo to the database by following this link , but it is not working. Here is the HTML code:

    <div class="form-group">
                <label asp-for="Foto" class="control-label"></label>
                <input asp-for="Foto" type="file" name="Img" id="Img" class="form-control" />
                <span asp-validation-for="Foto" class="text-danger"></span>
            </div>

The class I created:

public static class Utils
{
    public static string GetExtension(this IFormFile file)
    {
        return Path.GetExtension(file.FileName);
    }
    public static byte[] ToByteArray(this IFormFile file)
    {
        using (BinaryReader reader = new BinaryReader(file.OpenReadStream()))
        {
            return reader.ReadBytes((int)file.Length);
        }
    }
}

And here I try to pass this to the controller:

 public async Task<IActionResult> Novo(NovoViewModel model, IFormFile Img)
    {
        if (ModelState.IsValid)
        {
            var produto = new Produto
            {
                nome = model.Nome,
                Foto = Img.ToByteArray()

            };
             db.Add(produto);
            await db.SaveChangesAsync();
            return RedirectToAction("Editar", "Produto", new { id });
      }
    }

You are returning the following message:

  

NullReferenceException: Object reference not set to an instance of an object.

In the database the Foto field was created as follows.

public byte[] Foto { get; set; }

It returns error, in this line:

using (BinaryReader reader = new BinaryReader(file.OpenReadStream()))
    
asked by anonymous 17.09.2018 / 21:33

0 answers