How to upload images(several) to the Asp.net database

Asked

Viewed 49 times

0

I have a code in asp.net which aims to upload an image to the database, and I need to adapt it in order to move several up, only I have no idea how to do that. Follows the present code:

Model

    public int ClienteId { get; set; }
    [Required(ErrorMessage ="Informe o nome do cliente")]
    public string Nome { get; set; }
    [Required(ErrorMessage = "Informe o email do cliente")]
    [EmailAddress]
    public string Email { get; set; }
    [Required(ErrorMessage = "Informe o endereco do cliente")]
    public string Endereco { get; set; }
    public byte[] Imagem { get; set; }
    public string ImagemTipo { get; set; }

Controller

[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "ClienteId,Nome,Email,Endereco,Imagem,ImagemTipo")] Cliente cliente,HttpPostedFileBase upload)
    {
        if (ModelState.IsValid)
        {

            if (upload != null && upload.ContentLength > 0) {
                var arqImagem = new Cliente {
                    ImagemTipo=upload.ContentType
                };
                using (var reader = new BinaryReader(upload.InputStream))
                {
                    arqImagem.Imagem = reader.ReadBytes(upload.ContentLength);
                }
                cliente.Imagem = arqImagem.Imagem;
                cliente.ImagemTipo = arqImagem.ImagemTipo;
            }
            db.Clientes.Add(cliente);
            db.SaveChanges();
            TempData["mensagem"] = string.Format("{0} : for incluido com sucesso", cliente.Nome);
            return RedirectToAction("Catalogo");
        }
        return View(cliente);
    }

While trying to do this I modified the Image field in the model to:

** public Ienumerable Image { get; set; } **

and the controller like this:

 [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "ClienteId,Nome,Email,Endereco,Imagem,ImagemTipo")] Cliente cliente, HttpPostedFileBase upload)
    {
        if (ModelState.IsValid)
        {

            if (upload != null && upload.ContentLength > 0)
            {
                var arqImagem = new Cliente
                {
                    ImagemTipo = upload.ContentType
                };
                using (var reader = new BinaryReader(upload.InputStream))
                {

                    arqImagem.Imagem = reader.ReadBytes(upload.ContentLength);

                }
                cliente.Imagem = arqImagem.Imagem;
                cliente.ImagemTipo = arqImagem.ImagemTipo;
            }
            db.Clientes.Add(cliente);
            db.SaveChanges();
            TempData["mensagem"] = string.Format("{0} : for incluido com sucesso", cliente.Nome);
            return RedirectToAction("Catalogo");
        }
        return View(cliente);
    }

and I have the following mistake : Erro CS0029 Não é possível converter implicitamente tipo "byte[]" em "System.Collections.Generic.IEnumerable<byte[]>" EnumerableImagem

1 answer

0


Readbytes returns byte[], therefore in the allocation line of arqImagem.Imagem error when you change this property to IEnumerable.

public virtual byte[] ReadBytes (int count);

But there are more problems in your solution, your model represents the table in the database. You can’t just change the property to a IEnumerable. It is necessary to change the database structure by making this model customer relates to a model image in a relationship 1:N.

Would look like this:

public class Cliente
{
    public int ClienteId { get; set; }
    [Required(ErrorMessage ="Informe o nome do cliente")]
    public string Nome { get; set; }
    [Required(ErrorMessage = "Informe o email do cliente")]
    [EmailAddress]
    public string Email { get; set; }
    [Required(ErrorMessage = "Informe o endereco do cliente")]
    public string Endereco { get; set; }
    public int ImagemId { get; set; }
    public virtual ICollection<Imagem> Imagens { get; set; }
    public string ImagemTipo { get; set; }
}

public class Imagem
{
    public int ImagemId { get; set; }
    public byte[] Imagem { get; set; }
}

Remembering to make the necessary maps using DataNotations or FluentAPI.

Note also that if the database is in production you will need to migrate the images to the new table using the migration if using the Code First, but initially this is the procedure you should do to adjust your BD for 1 client relationship for N images.

  • Thanks for the fixes, buddy. About the conversion error.... it gives in the following line ' using (var Reader = new Binaryreader(upload.Inputstream)) { arqImage.Image = Reader.Readbytes(upload.Contentlength); }' how do I convert this to Working with Ienumerable? without making that mistake?

  • @Rafaelg, I put more detail in the answer.

Browser other questions tagged

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