1. Model: using System.ComponentModel.DataAnnotations; namespace MVC6App.Data { //this class will map the database entity. and we will use the byte[] to store the upload file content. public class Product { [Key] public int ProId { get; set; } public string ProName { get; set; } public string ProImageName { get; set; } public byte[] ProImageContent { get; set; } //you can add another properties } //this view model is used to collect the data and use the IFormFile to upload file. public class ProductViewModel { public string Name { get; set; } public IFormFile FormFile { get; set; } } } 2. Controller: using Microsoft.AspNetCore.Mvc; using MVC6App.Data; namespace MVC6App.Controllers { public class ProductController : Controller { private readonly ApplicationDbContext _dbcontext; public ProductController(ApplicationDbContext applicationDbContext) { _dbcontext = applicationDbContext; } public IActionResult Index() { var result = _dbcontext.Products.ToList(); return View(result); } public IActionResult Create() { return View(); } [HttpPost] public async Task CreateAsync(ProductViewModel product) { if (ModelState.IsValid) { //save image to database. using (var memoryStream = new MemoryStream()) { await product.FormFile.CopyToAsync(memoryStream); // Upload the file if less than 2 MB if (memoryStream.Length < 2097152) { //Convert the View mdoel to the database entity var file = new Product() { ProImageName = product.FormFile.FileName, ProImageContent = memoryStream.ToArray(), ProName = product.Name }; _dbcontext.Products.Add(file); await _dbcontext.SaveChangesAsync(); } else { ModelState.AddModelError("File", "The file is too large."); } } return RedirectToAction(nameof(Index)); } return View(); } } } 3. View page: @model MVC6App.Data.ProductViewModel @{ ViewData["Title"] = "Create"; Layout = "~/Views/Shared/_Layout.cshtml"; }

Create

ProductViewModel


Back to List
@section Scripts { @{await Html.RenderPartialAsync("_ValidationScriptsPartial");} }