Комо контроллер puedo settear una imagen por defecto en mi? Cuando el user никакой sube una imagen que automaticamente ponga una default: СИ никакой tienen imagen desde el controller de create, se распределяют una грех o desde la db o desde una imagen по умолчанию base64.
Model:
public IFormFile Foto { get; set; }
public string ImagePath { get; set; }
Контроллер:
public async Task<IActionResult> Create(Person person,IFormFile file)
{
if (ModelState.IsValid)
{
if (person.BirthYear == 0)
{
person.BirthYear = person.BirthDate.Value.Year;
}
if (file != null && file.Length > 0)
{
var ImagePath = @"/images2/";
var uploadPath = _env.WebRootPath + ImagePath;
if (!Directory.Exists(uploadPath))
{
Directory.CreateDirectory(uploadPath);
}
var uniqFileName = Guid.NewGuid().ToString();
var filename = Path.GetFileName(uniqFileName + "." + file.FileName.Split(".")[1].ToLower());
string fullPath = uploadPath + filename;
ImagePath = ImagePath + @"\";
var filePath = @".." + Path.Combine(ImagePath, filename);
using (var fileStream = new FileStream(fullPath, FileMode.Create))
{
await file.CopyToAsync(fileStream);
}
using (var ms = new MemoryStream())
{
file.CopyTo(ms);
var fileBytes = ms.ToArray();
string s = Convert.ToBase64String(fileBytes);
person.ImagePath = s;
}
_context.Add(person);
await _context.SaveChangesAsync();
ViewData["FileLocation"] = filePath;
}
return RedirectToRoute(new { controller = "People", action = "Details", id = person.PersonId });
}
return View(person);
}
Se que algo sencillo pero никакой consigo dar подставляет la tecla, se agradece por la ayuda C:
Пробуй спрашивая, если параметр file - null. Если это null тогда поиски изображение, которое у тебя будет в папке App_Data
, и ты добавляешь назначенную по умолчанию:
if (file != null && file.Length > 0)
{
//...
}
else{
// como file es null, entonces guardamos una imagen que sera la de por defecto
var defaultFile = Server.MapPath("~/App_Data/default_profiler_png.png");
// haces lo que tengas que hacer con la imagen
}
Это предполагая, что у тебя есть изображение в папке App_Data так называемая default_profiler_photo.png
.