I'm trying to upload an image, this is the view:
@model CrearAmigoModelo
@{
ViewBag.Title = "Nuevo amigo";
}
<form asp-controller="Home" asp-action="Create" method="post">
<div asp-validation-summary="All" > </div>
<div >
<label asp-for="Nombre" ></label>
<div >
<input asp-for="Nombre" placeholder="Nombre" />
<span asp-validation-for="Nombre" ></span>
</div>
</div>
<div >
<label asp-for="Email" ></label>
<div >
<input asp-for="Email" placeholder="E-mail" />
<span asp-validation-for="Email" ></span>
</div>
</div>
<div >
<label asp-for="Ciudad" ></label>
<div >
<select asp-for="Ciudad" asp-items="Html.GetEnumSelectList<Provincia>()">
:
<option value="">Seleccione uno</option>
</select>
<span asp-validation-for="Ciudad" ></span>
</div>
</div>
<div >
<label asp-for="Foto" >-------------------------</label>
<div >
<div >
<input type="file" asp-for="Foto" />
<label > Selecciona un fichero </label>
</div>
</div>
</div>
<div >
<div >
<button type="submit" >Nuevo</button>
</div>
</div>
@section Scripts{
<script>
$(document).ready(function() {
$('.custom-file-input').on("change", function (){
var fileName=$(this).val().split("\\").pop();
$(this).next('.custom-file-label').html(fileName);
});
});
</script>
}
</form>
This is the method in the controller:
[HttpPost]
public IActionResult Create(CrearAmigoModelo a)
{
if (ModelState.IsValid)
{
string guidImagen = null;
if (a.Foto != null)
{
string ficherosImagenes = Path.Combine(_env.WebRootPath, "images");
guidImagen = Guid.NewGuid().ToString() a.Foto.FileName;
string rutaDefinitiva = Path.Combine(ficherosImagenes, guidImagen);
a.Foto.CopyTo(new FileStream(rutaDefinitiva, FileMode.Create));
}
Amigo nuevoAmigo = new Amigo();
nuevoAmigo.Nombre = a.Nombre;
nuevoAmigo.Email = a.Email;
nuevoAmigo.Ciudad = a.Ciudad;
nuevoAmigo.rutaFoto = guidImagen;
//nuevoAmigo.rutaFoto = " ";
amigoAlmacen.nuevo(nuevoAmigo);
return RedirectToAction("details", new { id = nuevoAmigo.Id });
}
return View();
}
The controller gets null in the field "Foto", all the others fields are passed correctly. In the view when I complete all the fields and press the button to send the form, always show the message "The Foto field is required" even when I already selected the file.
CodePudding user response:
Forms that are going to include files need to have an encoding type of multipart/form-data
.
<form enctype="multipart/form-data">
</form>
Please reference the following Microsoft Docs for more information: