How to save an attribute to image

Asked

Viewed 627 times

0

I need to save an image and 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 stay saved on the system, which I would need to save and display the user’s photo?

  • 1

    Do you want to save where? From where? Display where? Have you ever tried to do anything? If you have tried, put the code.

  • @Ricardo It is a web system, a system user can edit his profile, send an image of his machine and be saved in the database connected to the system. I didn’t try, I heard of the type Blob, but I don’t know how to use, I didn’t find anything very clear on the Internet.

  • The photo file has to stay in the database or it can be stored in a server folder and the database only saves the link to the file?

2 answers

5


In an ASP.NET MVC system, what you’re looking for is the classic upload files. I will explain to a file only, and this scheme does not only serve for photos, but serves as a start.

First, you will save in Model the file path, not the file itself. You can even save the file in the database, but this will get very complicated, and it is 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 admit the photo. I don’t know what your Controller, but I’ll put a cliché that should answer:

    [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.
        }
    }

Note that I have taken several freedoms. One of them is to determine a directory of upload called Uploads solution. It doesn’t have to be like this. It could be another directory. I did it 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" })
}

That’s the least you can do to make it work. If you need anything, just say.


EDIT

It is prerequisite for the answer that is saved in bank, so I will make some addenda.

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.

2

It depends on what you want to do, if you want the photo to be there, probably the way is to use Image. Even if the photo is stored elsewhere you may want to load it into memory to put in this class property called Foto. You have utilitarian methods for this.

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

The issue of upload is already something else. I would probably use the HttpPostedFileBase (I don’t know if it’s a good idea for more modern codes in ASP.NET MVC). It has a complete example using database with Entity Framework (I am not saying that this is suitable for you).

Browser other questions tagged

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