Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.IO;
- using System.Linq;
- using System.Threading.Tasks;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.AspNetCore.Mvc;
- using ProjectApplicationX00140684.Models;
- using Microsoft.AspNetCore.Mvc.Infrastructure;
- namespace ProjectApplicationX00140684.Controllers
- {
- public class HomeController : Controller
- {
- private readonly IVehicleRepository _vehicleRepository;
- private readonly IHostingEnvironment hostingEnvironment;
- public HomeController(IVehicleRepository vehicleRepository,
- IHostingEnvironment hostingEnvironment)
- {
- _vehicleRepository = vehicleRepository;
- this.hostingEnvironment = hostingEnvironment;
- }
- public ViewResult Index()
- {
- var model = _vehicleRepository.GetAllVehicle();
- return View(model);
- }
- [HttpGet]
- public ViewResult Create()
- {
- return View();
- }
- [HttpPost]
- public IActionResult Create(VehicleCreateViewModel model)
- {
- if (ModelState.IsValid)
- {
- string uniqueFileName = null;
- // If the Photo property on the incoming model object is not null, then the user
- // has selected an image to upload.
- if (model.Photo != null)
- {
- // The image must be uploaded to the images folder in wwwroot
- // To get the path of the wwwroot folder we are using the inject
- // HostingEnvironment service provided by ASP.NET Core
- string uploadsFolder = Path.Combine(hostingEnvironment.WebRootPath, "images");
- // To make sure the file name is unique we are appending a new
- // GUID value and and an underscore to the file name
- uniqueFileName = Guid.NewGuid().ToString() + "_" + Path.GetFileName(model.Photo.FileName);
- string filePath = Path.Combine(uploadsFolder, uniqueFileName);
- // Use CopyTo() method provided by IFormFile interface to
- // copy the file to wwwroot/images folder
- model.Photo.CopyTo(new FileStream(filePath, FileMode.Create));
- }
- Vehicle newVehicle = new Vehicle
- {
- Make = model.Make,
- Model = model.Model,
- Year = model.Year,
- // Store the file name in PhotoPath property of the employee object
- // which gets saved to the Employees database table
- PhotoPath = uniqueFileName
- };
- _vehicleRepository.Add(newVehicle);
- return RedirectToAction("index", new { id = newVehicle.VehicleID });
- }
- return View();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement