Save photo in MVC

Asked

Viewed 31 times

1

I’m trying to save photo in the database by following this link, but it’s 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 like 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 to me:

Nullreferenceexception: Object Reference not set to an instance of an Object.

On the bench the field Foto was created as follows.

public byte[] Foto { get; set; }

It returns error on this line:

using (BinaryReader reader = new BinaryReader(file.OpenReadStream()))
  • On which line is it returning the error? It’s in your transformation class or your controller?

  • @Victorlaio edited the question with the line where the error returns.

  • The file arrives in the Tobytearray filled method?

  • No @devgirl it arrives null.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.