Saving an attribute for image [closed]

0

I need to save an image and let's say I have something like:

namespace Projeto.Models
{
    public class Usuario
    {
        public int UserId { get; set; }

        public String Nome { get; set; }

        public ? Foto { get; set; }
    }
}

Being a web system, where the user could upload the image and get saved on the system, what would I need to save and display the user's photo?

    
asked by anonymous 06.01.2016 / 20:47

2 answers

5

In an ASP.NET MVC system, what you are looking for is the classic upload scheme of files. I'll explain to a file only, and this scheme is not just for photos, but serves as a start.

First, you will save in Model the path of the file, not the file itself. You can even save the file in the database, but this will be very complicated, and it's not the idea of the answer, so modify your Model to the following:

namespace Projeto.Models
{
    public class Usuario
    {
        public int UserId { get; set; }

        public String Nome { get; set; }
        public String CaminhoFoto { get; set; } // Aqui é o que vai ser efetivamente salvo

        [NotMapped]
        public HttpPostedFileBase Foto { get; set; } // Este campo não é salvo. Serve apenas para a tela
    }
}

Once this is done, we need to modify the Controller to support the photo. I do not know how your Controller is, but I'm going to put a cliché that should meet:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Criar([Bind(Include="UserId,Nome,Foto")] Usuario usuario)
    {
        if (usuario.Foto != null && usuario.Foto.ContentLength > 0)
        {
            string caminho = Path.Combine(Server.MapPath("~/Uploads/Usuarios/"), usuario.Foto.FileName);
            usuario.Foto.SaveAs(caminho);
            usuario.CaminhoFoto = usuario.Foto.FileName;
        }

        if (ModelState.IsValid)
        {
            // Aqui você salva o Model normalmente.
        }
    }

Please note that I have taken several liberties. One is to determine a upload directory called Uploads within the solution. It does not have to be this way. Could be another directory. I did for example.

Now, let's go to View :

@model Projeto.Models.Usuario

@using (Html.BeginForm("Criar", "Usuarios", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.TextBoxFor(model => model.Foto, new { type = "file", @class = "form-control", accept = ".jpg,.jpeg,.png" })
}

There you have the minimum so that everything works. If you need anything, just say it.

EDIT

It is a prerequisite for the answer that is saved in a bank, so I'll make some addendums.

Model

namespace Projeto.Models
{
    public class Usuario
    {
        public int UserId { get; set; }

        public String Nome { get; set; }
        public byte[] ConteudoFoto { get; set; }

        [NotMapped]
        public HttpPostedFileBase Foto { get; set; } // Este campo não é salvo. Serve apenas para a tela
    }
}

Controller

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Criar([Bind(Include="UserId,Nome,Foto")] Usuario usuario)
    {
        if (usuario.Foto != null && usuario.Foto.ContentLength > 0)
        {
            using (var binaryReader = new BinaryReader(usuario.Foto.InputStream))
            {
                usuario.ConteudoFoto = binaryReader.ReadBytes(usuario.Foto.ContentLength);
            }
        }

        if (ModelState.IsValid)
        {
            // Aqui você salva o Model normalmente.
        }
    }

View looks the same.

    
06.01.2016 / 22:17
2

Depending on what you want to do, if you want the photo to be there, the path is likely to use Image ". Even if the photo is stored elsewhere, you may want to load it into memory to by in this property of the class named Foto . It has utilitarian methods for this.

If you just want to use a reference for the photo that will be in a file or another location, then just use string itself and it will have the location of the photo (URI or key where it is, for example) p>

The upload issue is already something else. You would probably use HttpPostedFileBase (which I I do not know if it's a good idea for more modern code in ASP.Net MVC). You have a complete example using bank of Data with Entity Framework (I'm not saying this is the right one for you).

    
06.01.2016 / 21:04