Добавил логику загрузки файла (или аватарки Person)

parent e9d79ea8
using System.IO;
using Microsoft.AspNetCore.Mvc;
using MyCities.Models;
using MyCities.Repositories;
using MyCities.ViewModels;
namespace MyCities.Controllers
{
......@@ -12,10 +15,26 @@ namespace MyCities.Controllers
_repository = repository;
}
// GET
public IActionResult Index()
{
return View(_repository.Persons);
}
[HttpGet]
public IActionResult Create()
{
return View();
}
[HttpPost]
public IActionResult Create(PersonCreateViewModel viewModel)
{
using (var stream = new FileStream(viewModel.GetFilePath(), FileMode.Create))
{
viewModel.Avatar.CopyTo(stream);
}
_repository.Add(viewModel.GetPerson());
return RedirectToAction("Index");
}
}
}
using System.IO;
using Microsoft.AspNetCore.Http;
using MyCities.Models;
namespace MyCities.ViewModels
{
public class PersonCreateViewModel
{
public string FullName { get; set; }
public string NickName { get; set; }
public IFormFile Avatar { get; set; }
public string GetFilePath()
{
return Path.Combine(
Directory.GetCurrentDirectory(),
"wwwroot",
"images",
Avatar.FileName
);
}
public string GetAvatarImagePath()
{
return Path.Combine(
"images",
Avatar.FileName
);
}
public Person GetPerson()
{
return new Person
{
FullName = FullName,
NickName = NickName,
AvatarImagePath = GetAvatarImagePath()
};
}
}
}
......@@ -19,7 +19,4 @@
</div>
<button type="submit" hlp-color="primary">Create</button>
<mysuperbtn></mysuperbtn>
<button type="submit" class="btn btn-primary">Clear</button>
<a asp-controller="Home" asp-actoin="Index" class="btn btn-primary">Cancel</a>
</form>
@{
Layout = "_Layout";
}
<form asp-controller="Person" asp-action="Create" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="FullName">FullName:</label>
<input class="form-control" name="FullName"/>
</div>
<div class="form-group">
<label for="Nickname">Nickname:</label>
<input class="form-control" name="Nickname"/>
</div>
<div class="form-group">
<label for="Avatar">Avatar</label>
<input type="file" class="form-control-file" name="Avatar">
</div>
<button type="submit" hlp-color="primary">Create</button>
</form>
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment