Commit 55a0af92 authored by TTrueBenji's avatar TTrueBenji

Добавить загрузку файла.

***
Добавил тестовый функционал загрузки файла на сервер.
***
parent 042a5e29
using System.Collections.Generic;
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Hosting;
using PhoneStore.Models;
using PhoneStore.Services;
using PhoneStore.ViewModels;
namespace PhoneStore.Controllers
{
public class PhonesController : Controller
{
private readonly MobileContext _db;
private readonly IHostEnvironment _environment;
private readonly UploadService _uploadService;
public PhonesController(MobileContext db)
public PhonesController(
MobileContext db,
IHostEnvironment environment, UploadService uploadService)
{
_db = db;
_environment = environment;
_uploadService = uploadService;
}
/// <summary>
/// Действие, которое возвращает страницу со списком смартфонов
/// </summary>
/// <returns></returns>
[HttpGet]
public IActionResult Index()
public IActionResult Index(int? id, string? name)
{
List<Phone> phones = _db.Phones.ToList();
return View(phones);
var phones = _db.Phones.AsQueryable();
if (id.HasValue)
{
phones = _db.Phones.Where(p => p.Id == id);
}
if (!string.IsNullOrEmpty(name))
{
phones = phones.Where(p => string.Equals(p.Name, name, StringComparison.CurrentCultureIgnoreCase));
}
var phoneList = phones.ToList();
return View(phones.ToList());
}
[HttpGet]
......@@ -86,5 +105,22 @@ namespace PhoneStore.Controllers
_db.SaveChanges();
return RedirectToAction("Index");
}
[HttpGet]
public IActionResult UploadFile()
{
return View();
}
[HttpPost]
public async Task<IActionResult> UploadFile(FileViewModel model)
{
string dirPath = Path.Combine(_environment.ContentRootPath, "wwwroot/Files");
string fileName = $"{model.File.FileName}";
await _uploadService.UploadAsync(dirPath, fileName, model.File);
return Ok("Файл успешно загружен");
}
}
}
\ No newline at end of file
......@@ -17,7 +17,6 @@
</ItemGroup>
<ItemGroup>
<Folder Include="Phones" />
<Folder Include="Migrations" />
</ItemGroup>
......
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
namespace PhoneStore.Services
{
public class UploadService
{
public async Task UploadAsync(string dirPath, string fileName, IFormFile file)
{
await using var stream = new FileStream(Path.Combine(dirPath, fileName), FileMode.Create);
await file.CopyToAsync(stream);
}
}
}
\ No newline at end of file
......@@ -20,16 +20,15 @@ namespace PhoneStore
}
public IConfiguration Configuration { get; }
private IServiceCollection _services;
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
_services = services;
string connection = Configuration.GetConnectionString("DefaultConnection");
services.AddDbContext<MobileContext>(options => options.UseSqlite(connection));
services.AddControllersWithViews();
services.AddScoped<IBasketService, BasketService>();
services.AddTransient<UploadService>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
......
using Microsoft.AspNetCore.Http;
namespace PhoneStore.ViewModels
{
public class FileViewModel
{
public IFormFile File { get; set; }
}
}
\ No newline at end of file
......@@ -66,9 +66,7 @@ else
</tr>
}
</table>
<div class="d-flex justify-content-end my-5">
<a class="btn btn-outline-info" asp-action="Create" asp-controller="Phones">Добавить устройство</a>
</div>
}
<div class="d-flex justify-content-end my-5">
<a class="btn btn-outline-info" asp-action="Create" asp-controller="Phones">Добавить устройство</a>
</div>
@model FileViewModel
@{
ViewBag.Title = "Загрузка файла";
Layout = "_Layout";
}
<h2>Загрузите файл на сервер</h2>
<form asp-action="UploadFile" asp-controller="Phones" method="post" enctype="multipart/form-data">
<fieldset>
<div class="mb-3">
<div class="form-check">
<input class="form-check-input" type="file" asp-for="File">
<label class="form-check-label" asp-for="File">
Добавьте файл
</label>
</div>
</div>
<button type="submit" class="btn btn-outline-info">Добавить</button>
</fieldset>
</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