From 894d4e3f228c299c5ec7ffd94b13a7baa0764e63 Mon Sep 17 00:00:00 2001 From: "DESKTOP-GENO133\\IvanPlex" Date: Mon, 1 Jan 2024 20:40:08 -0700 Subject: [PATCH] Added Async File Upload. --- Controllers/FilesController.cs | 47 ++++++++++++++++++++++ Controllers/HomeController.cs | 63 +++-------------------------- Models/VehicleInputModel.cs | 12 ------ Views/Home/Index.cshtml | 22 +++++------ wwwroot/js/garage.js | 72 +++++++++++++++++++++++++++++++++- 5 files changed, 133 insertions(+), 83 deletions(-) create mode 100644 Controllers/FilesController.cs delete mode 100644 Models/VehicleInputModel.cs diff --git a/Controllers/FilesController.cs b/Controllers/FilesController.cs new file mode 100644 index 0000000..2cd224f --- /dev/null +++ b/Controllers/FilesController.cs @@ -0,0 +1,47 @@ +using CarCareTracker.External.Interfaces; +using CarCareTracker.Models; +using LiteDB; +using Microsoft.AspNetCore.Mvc; +using System.Diagnostics; +using static System.Net.Mime.MediaTypeNames; +using System.Drawing; +using System.Linq.Expressions; +using Microsoft.Extensions.Logging; + +namespace CarCareTracker.Controllers +{ + public class FilesController : Controller + { + private readonly ILogger _logger; + private readonly IVehicleDataAccess _dataAccess; + private readonly IWebHostEnvironment _webEnv; + + public FilesController(ILogger logger, IWebHostEnvironment webEnv) + { + _logger = logger; + _webEnv = webEnv; + } + + [HttpPost] + public IActionResult HandleFileUpload(IFormFile file) + { + var fileName = UploadImage(file); + return Json(fileName); + } + + private string UploadImage(IFormFile fileToUpload) + { + string uploadDirectory = "images/"; + string uploadPath = Path.Combine(_webEnv.WebRootPath, uploadDirectory); + if (!Directory.Exists(uploadPath)) + Directory.CreateDirectory(uploadPath); + string fileName = Guid.NewGuid() + Path.GetExtension(fileToUpload.FileName); + string filePath = Path.Combine(uploadPath, fileName); + using (var stream = System.IO.File.Create(filePath)) + { + fileToUpload.CopyTo(stream); + } + return Path.Combine("/", uploadDirectory, fileName); + } + } +} diff --git a/Controllers/HomeController.cs b/Controllers/HomeController.cs index c26b764..512b872 100644 --- a/Controllers/HomeController.cs +++ b/Controllers/HomeController.cs @@ -23,12 +23,8 @@ namespace CarCareTracker.Controllers _webEnv = webEnv; } - public IActionResult Index(VehicleInputModel? initialModel) + public IActionResult Index() { - if (initialModel is not null && initialModel.Errors is not null) - { - return View(initialModel); - } return View(); } public IActionResult Garage() @@ -41,53 +37,19 @@ namespace CarCareTracker.Controllers return View(); } [HttpPost] - public IActionResult AddVehicle(VehicleInputModel vehicleInput) + public IActionResult AddVehicle(Vehicle vehicleInput) { - var errors = new List(); - //validation - if (vehicleInput.Year < 1900) - errors.Add("Year is invalid"); - if (string.IsNullOrWhiteSpace(vehicleInput.Make)) - errors.Add("Make is required"); - if (string.IsNullOrWhiteSpace(vehicleInput.Model)) - errors.Add("Model is required"); - if (string.IsNullOrWhiteSpace(vehicleInput.LicensePlate)) - errors.Add("License Plate is required"); - if (errors.Any()) - { - vehicleInput.Errors = errors; - return RedirectToAction("Index", "Home", vehicleInput); - } - try { - //map vehicleInput to vehicle object. - var newVehicle = new Vehicle - { - Year = vehicleInput.Year, - Make = vehicleInput.Make, - Model = vehicleInput.Model, - LicensePlate = vehicleInput.LicensePlate - }; - if (vehicleInput.Image is not null) - { - string imagePath = UploadImage(vehicleInput.Image); - if (!string.IsNullOrWhiteSpace(imagePath)) - { - newVehicle.ImageLocation = imagePath; - } - } //save vehicle. - var result = _dataAccess.SaveVehicle(newVehicle); - RedirectToAction("Index"); + var result = _dataAccess.SaveVehicle(vehicleInput); + return Json(result); } catch(Exception ex) { _logger.LogError(ex, "Error Saving Vehicle"); - vehicleInput.Errors = new List { "Error Saving Vehicle, Please Try Again Later" }; - return RedirectToAction("Index", "Home", vehicleInput); + return Json(false); } - return RedirectToAction("Index"); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] @@ -95,20 +57,5 @@ namespace CarCareTracker.Controllers { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } - - private string UploadImage(IFormFile fileToUpload) - { - string uploadDirectory = "images/"; - string uploadPath = Path.Combine(_webEnv.WebRootPath, uploadDirectory); - if (!Directory.Exists(uploadPath)) - Directory.CreateDirectory(uploadPath); - string fileName = Guid.NewGuid() + Path.GetExtension(fileToUpload.FileName); - string filePath = Path.Combine(uploadPath, fileName); - using (var stream = System.IO.File.Create(filePath)) - { - fileToUpload.CopyTo(stream); - } - return Path.Combine("/", uploadDirectory, fileName); - } } } diff --git a/Models/VehicleInputModel.cs b/Models/VehicleInputModel.cs deleted file mode 100644 index eb89e25..0000000 --- a/Models/VehicleInputModel.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace CarCareTracker.Models -{ - public class VehicleInputModel - { - public int Year { get; set; } - public string Make { get; set; } - public string Model { get; set; } - public string LicensePlate { get; set; } - public IFormFile Image { get; set; } - public List Errors { get; set; } - } -} diff --git a/Views/Home/Index.cshtml b/Views/Home/Index.cshtml index 38e9cea..6b375e1 100644 --- a/Views/Home/Index.cshtml +++ b/Views/Home/Index.cshtml @@ -1,13 +1,12 @@ @{ ViewData["Title"] = "My Garage"; } -@model VehicleInputModel -@section Scripts{ +@section Scripts { } @if (Model is not null && Model.Errors.Any()) { - foreach(string error in Model.Errors) + foreach (string error in Model.Errors) {