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.