Asp Net Core File Upload Image Entity Framework
Suggested Videos
Part 50 - Entity framework core migrations | Text | Slides
Part 51 - Entity framework core seed data | Text | Slides
Part 52 - Keeping domain models and database schema in sync in asp.internet core | Text | Slides
In this video we will talk over how to upload a file using ASP.NET Core MVC with an instance.
We desire to implement the post-obit Create Employee Form . We want to exist able upload Employee photo using the Photo field on the form.
When this Create Employee Form is submitted, we want to shop Employee data i.e Proper name, Email, Department and PhotoPath in Employees database table. Here is the Employees database table. This table is created using Migrations in ASP.Cyberspace Core.
Employee photograph should be uploaded to wwwroot/images folder on the web server.
Employee Model Class
public course Employee
{
public int Id { get ; ready ; }
public string Proper name { get ; set ; }
public string Email { become ; set ; }
public Dept ? Department { get ; set ; }
public string PhotoPath { get ; set ; }
}
EmployeeCreateViewModel Course
public grade CreateViewModel
{
public string Name { get ; set ; }
public string Email { become ; fix ; }
public Dept ? Department { get ; set up ; }
public IFormFile Photo { become ; set ; }
}
- IFormFile is in Microsoft.AspNetCore.Http namespace.
- The file uploaded to the server can exist accessed through Model Binding using the IFormFile interface.
- The interface IFormFile has the following properties and methods
public interface IFormFile
{
cord ContentType { go ; }
string ContentDisposition { get ; }
IHeaderDictionary Headers { get ; }
long Length { get ; }
string Name { get ; }
cord FileName { get ; }
Stream OpenReadStream();
void CopyTo( Stream target);
Chore CopyToAsync( Stream target, CancellationToken cancellationToken = nothing );
}
Create View Lawmaking
The code specific to uploading the file is commented
@model EmployeeCreateViewModel
@{
ViewBag.Title = "Create Employee" ;
}
@* To support file upload set the form element enctype="multipart/form-information" *@
< form enctype ="multipart/form-data" asp-controller ="home" asp-activeness ="create"
method ="mail service" class ="mt-3">
< div class ="form-grouping row">
< label asp-for =" Name " class ="col-sm-2 col-form-label"></ label >
< div class ="col-sm-10">
< input asp-for =" Proper noun " class ="grade-control" placeholder ="Name">
< span asp-validation-for =" Name " course ="text-danger"></ span >
</ div >
</ div >
< div class ="form-group row">
< label asp-for =" E-mail " grade ="col-sm-2 col-form-characterization"></ label >
< div class ="col-sm-10">
< input asp-for =" Email " class ="form-control" placeholder ="Electronic mail">
< bridge asp-validation-for =" Email " class ="text-danger"></ span >
</ div >
</ div >
< div grade ="form-grouping row">
< label asp-for =" Section " course ="col-sm-ii col-form-label"></ label >
< div class ="col-sm-10">
< select asp-for =" Department " class ="custom-select mr-sm-two"
asp-items =" Html.GetEnumSelectList<Dept>() ">
< pick value =""> Delight Select </ option >
</ select >
< bridge asp-validation-for =" Section " class ="text-danger"></ span >
</ div >
</ div >
@* asp-for tag helper is set to "Photo" property. "Photo" property type is IFormFile
and then at runtime asp.internet core generates file upload control (input type=file)
*@
< div class ="form-group row">
< label asp-for =" Photograph " class ="col-sm-2 col-class-characterization"></ label >
< div class ="col-sm-10">
< div form ="custom-file">
< input asp-for =" Photo " class ="form-control custom-file-input">
< characterization class ="custom-file-label"> Choose File... </ label >
</ div >
</ div >
</ div >
< div asp-validation-summary =" All " course ="text-danger"></ div >
< div class ="course-group row">
< div grade ="col-sm-10">
< button blazon ="submit" course ="btn btn-primary"> Create </ button >
</ div >
</ div >
@* This script is required to display the selected file in the file upload chemical element *@
@department Scripts {
< script >
$(document).fix( office () {
$( '.custom-file-input' ).on( "alter" , role () {
var fileName = $( this ).val().divide( "\\" ).pop();
$( this ).next( '.custom-file-characterization' ).html(fileName);
});
});
</ script >
}
</ form >
Create Action Method
using EmployeeManagement.Models;
using EmployeeManagement.ViewModels;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using System;
using System.IO;
namespace EmployeeManagement.Controllers
{
public form HomeController : Controller
{
individual readonly IEmployeeRepository _employeeRepository;
private readonly IHostingEnvironment hostingEnvironment;
public HomeController(IEmployeeRepository employeeRepository,
IHostingEnvironment hostingEnvironment)
{
_employeeRepository = employeeRepository;
this .hostingEnvironment = hostingEnvironment;
}
[HttpGet]
public ViewResult Create()
{
render View();
}
[HttpPost]
public IActionResult Create(EmployeeCreateViewModel model)
{
if (ModelState.IsValid)
{
string uniqueFileName = null ;
// If the Photograph property on the incoming model object is non nada, and so the user
// has selected an image to upload.
if (model.Photo != aught )
{
// The image must exist 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 Cadre
string uploadsFolder = Path.Combine(hostingEnvironment.WebRootPath, "images" );
// To make sure the file proper name is unique we are appending a new
// GUID value and and an underscore to the file proper name
uniqueFileName = Guid.NewGuid().ToString() + "_" + model.Photo.FileName;
string filePath = Path.Combine(uploadsFolder, uniqueFileName);
// Use CopyTo() method provided past IFormFile interface to
// copy the file to wwwroot/images folder
model.Photo.CopyTo( new FileStream(filePath, FileMode.Create));
}
Employee newEmployee = new Employee
{
Name = model.Name,
Email = model.Electronic mail,
Department = model.Section,
// Store the file proper noun in PhotoPath holding of the employee object
// which gets saved to the Employees database table
PhotoPath = uniqueFileName
};
_employeeRepository.Add(newEmployee);
return RedirectToAction( "details" , new { id = newEmployee.Id });
}
return View();
}
}
}
The rest of the code on this page is not required to upload a file. It contains lawmaking to display a specific employee details using the details view and the list of employees using the index view.
Details View Lawmaking
@model HomeDetailsViewModel
@{
ViewBag.Title = "Employee Details" ;
var photoPath = "~/images/" + (Model.Employee.PhotoPath ?? "noimage.jpg" );
}
< div form ="row justify-content-center m-3">
< div course ="col-sm-8">
< div class ="card">
< div class ="card-header">
< h1 > @ Model.Employee.Name </ h1 >
</ div >
< div class ="card-body text-center">
< img form ="card-img-summit" src =" @ photoPath " asp-append-version ="true" />
< h4 > Employee ID : @Model.Employee.Id </ h4 >
< h4 > Email : @Model.Employee.Email </ h4 >
< h4 > Department : @Model.Employee.Department </ h4 >
</ div >
< div course ="bill of fare-footer text-center">
< a asp-controller ="dwelling" asp-activeness ="alphabetize" grade ="btn btn-primary"> Back </ a >
< a href ="#" class ="btn btn-main"> Edit </ a >
< a href ="#" class ="btn btn-danger"> Delete </ a >
</ div >
</ div >
</ div >
</ div >
Alphabetize View Code
@model IEnumerable < Employee >
@{
ViewBag.Title = "Employee List" ;
}
< div grade ="card-deck">
@ foreach (var employee in Model)
{
var photoPath = "~/images/" + (employee.PhotoPath ?? "noimage.jpg" );
< div form ="bill of fare m-3" style =" min-width : 18rem ; max-width : 30.five% ; ">
< div class ="carte du jour-header">
< h3 > @ employee.Name </ h3 >
</ div >
< img class ="card-img-top imageThumbnail" src =" @ photoPath "
asp-append-version ="true" />
< div class ="bill of fare-footer text-center">
< a asp-controller ="home" asp-action ="details" asp-route-id =" @ employee.Id "
class ="btn btn-chief thousand-1"> View </ a >
< a href ="#" class ="btn btn-main g-1"> Edit </ a >
< a href ="#" class ="btn btn-danger m-1"> Delete </ a >
</ div >
</ div >
}
</ div >
site.css
.imageThumbnail {
height : 200px ;
width : auto ;
}
Source: https://csharp-video-tutorials.blogspot.com/2019/05/file-upload-in-aspnet-core-mvc.html
0 Response to "Asp Net Core File Upload Image Entity Framework"
Post a Comment