Follow us

Header Ads

ImageUpload Functionality in Asp.net Core

 ImageUpload

Install Package

  • "Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="3.1.5" 
  •  "Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.25" 
  • "Microsoft.EntityFrameworkCore.Tools" Version="3.1.25"
  • "Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="3.1.5"

launchSettings.json

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:44709",
      "sslPort": 0
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        //"ASPNETCORE_ENVIRONMENT": "Development"
        "ASPNETCORE_ENVIRONMENT": "Production"
      }
    },
    "ImageUpload": {
      "commandName": "Project",
      "launchBrowser": true,
      "applicationUrl": "http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"        
      }
    }
  }
}

Create Folder wwwroot->Images[Create folder Images in wwwroot Folder]

Controllers[Folder]

FirstStudentsController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using ImageUpload.Data;
using ImageUpload.Models;

namespace ImageUpload.Controllers
{
    public class FirstStudentsController : Controller
    {
        private readonly ApplicationDbContext _context;

        public FirstStudentsController(ApplicationDbContext context)
        {
            _context = context;
        }

        // GET: FirstStudents
        public async Task<IActionResult> Index()
        {
            return View(await _context.FirstStudents.ToListAsync());
        }

        // GET: FirstStudents/Details/5
        public async Task<IActionResult> Details(int? id)
        {
            if (id == null)
            {
                return View("NotFound",id);
            }

            var firstStudent = await _context.FirstStudents
                .FirstOrDefaultAsync(m => m.Id == id);
            if (firstStudent == null)
            {
                return View("NotFound",id);
            }

            return View(firstStudent);
        }

        // GET: FirstStudents/Create
        public IActionResult Create()
        {
            return View();
        }

        // POST: FirstStudents/Create
        // To protect from overposting attacks, enable the specific properties you want to bind to, for 
        // more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("Id,Name,City,Email")] FirstStudent firstStudent)
        {
            if (ModelState.IsValid)
            {
                _context.Add(firstStudent);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            return View(firstStudent);
        }

        // GET: FirstStudents/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var firstStudent = await _context.FirstStudents.FindAsync(id);
            if (firstStudent == null)
            {
                return NotFound();
            }
            return View(firstStudent);
        }

        // POST: FirstStudents/Edit/5
        // To protect from overposting attacks, enable the specific properties you want to bind to, for 
        // more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, [Bind("Id,Name,City,Email")] FirstStudent firstStudent)
        {
            if (id != firstStudent.Id)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(firstStudent);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!FirstStudentExists(firstStudent.Id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            return View(firstStudent);
        }

        // GET: FirstStudents/Delete/5
        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var firstStudent = await _context.FirstStudents
                .FirstOrDefaultAsync(m => m.Id == id);
            if (firstStudent == null)
            {
                return NotFound();
            }

            return View(firstStudent);
        }

        // POST: FirstStudents/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            var firstStudent = await _context.FirstStudents.FindAsync(id);
            _context.FirstStudents.Remove(firstStudent);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }

        private bool FirstStudentExists(int id)
        {
            return _context.FirstStudents.Any(e => e.Id == id);
        }
    }
}


HomeController.cs

using ImageUpload.Data;                                                                                                                                                                                                                                               
using ImageUpload.Models;
using ImageUpload.ViewModel;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace ImageUpload.Controllers
{
    public class HomeController : Controller
    {
        private readonly ApplicationDbContext Context;
        private readonly IWebHostEnvironment WebHostEnvironment;

        public HomeController(ApplicationDbContext context,
            IWebHostEnvironment webHostEnvironment)
        {
            Context = context;
            WebHostEnvironment = webHostEnvironment;
        }
        public IActionResult Index()
        {
            var items = Context.Students.ToList();
            return View(items);
        }
        public IActionResult Create()
        {
            return View();
        }
        [HttpPost]
        public IActionResult Create(StudentViewModel vm)
        {
            string stringFileName = UploadFile(vm);
            var Student = new Student
            {
                Name = vm.Name,
                ProfileImage = stringFileName
            };
            Context.Students.Add(Student);
            Context.SaveChanges();
            return RedirectToAction("Index");

        }

        private string UploadFile(StudentViewModel vm)
        {
            string fileName = null;
            if (vm.ProfileImage != null)
            {
                string uploadDir = Path.Combine(WebHostEnvironment.WebRootPath, "Images");
                fileName = Guid.NewGuid().ToString() + "_" + vm.ProfileImage.FileName;
                string filePath = Path.Combine(uploadDir, fileName);
                using (var fileStream = new FileStream(filePath, FileMode.Create))
                {
                    vm.ProfileImage.CopyTo(fileStream);
                }
            }
            return fileName;
        }
    }

}

TestController.cs

using ImageUpload.Data;
using Microsoft.AspNetCore.Mvc;
using System.Linq;

namespace ImageUpload.Controllers
{
    public class TestController : Controller
    {
        private readonly ApplicationDbContext _context;

        public TestController(ApplicationDbContext context)
        {
            _context = context;
        }
        public IActionResult Index()
        {
            var student = _context.Students.ToList();            
            return View(student);
        }
    }
}

Data[Folder]

ApplicationDbContext.cs

using ImageUpload.Models;
using Microsoft.EntityFrameworkCore;

namespace ImageUpload.Data
{
    public class ApplicationDbContext :DbContext
    {
      public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) :base(options)
        {

        }
        public DbSet<Student> Students { get; set; }
        public DbSet<FirstStudent> FirstStudents { get; set; }
        // Seed Data
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<FirstStudent>().HasData(
            new FirstStudent { Id = 11, Name = "Tarun11", Email = "xyz11@outlook.com" , City="Patna11" },
            new FirstStudent { Id = 12, Name = "Tarun22", Email = "xyz21@outlook.com", City = "Patna22" }
                );
        }
    }
}

Models[Folder]

FirstStudent.cs

using System.ComponentModel.DataAnnotations;

namespace ImageUpload.Models
{
    public class FirstStudent
    {
        [Key]
        public int Id { get; set; }
        [Required]
        [Display(Name="Full Name")]
        [MaxLength(50,ErrorMessage ="Name is Required Field & Less than 50 Characters")]
        public string Name { get; set; }
        [Required]
        public string City { get; set; }
        [Required]
        [EmailAddress]
        public string Email { get; set; }
    }
}

Student.cs

namespace ImageUpload.Models
{
    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string ProfileImage { get; set; }
    }
}

ViewModel[Folder]

StudentViewModel.cs

using Microsoft.AspNetCore.Http;

namespace ImageUpload.ViewModel
{
    public class StudentViewModel
    {
        public string Name { get; set; }   
        //It can automatically create file upload control
        public IFormFile ProfileImage { get; set; }
    }
}

Views[Folder]

FirstStudents

Create.cshtml

@model ImageUpload.Models.FirstStudent

@{
    ViewData["Title"] = "Create";
}

<h1>Create</h1>

<h4>FirstStudent</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Create">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div asp-validation-summary="All" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Name" class="control-label"></label>
                <input asp-for="Name" class="form-control" />
                <span asp-validation-for="Name" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="City" class="control-label"></label>
                <input asp-for="City" class="form-control" />
                <span asp-validation-for="City" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Email" class="control-label"></label>
                <input asp-for="Email" class="form-control" />
                <span asp-validation-for="Email" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>

Delete.cshtml

@model ImageUpload.Models.FirstStudent

@{
    ViewData["Title"] = "Delete";
}

<h1>Delete</h1>

<h3>Are you sure you want to delete this?</h3>
<div>
    <h4>FirstStudent</h4>
    <hr />
    <dl class="row">
        <dt class = "col-sm-2">
            @Html.DisplayNameFor(model => model.Name)
        </dt>
        <dd class = "col-sm-10">
            @Html.DisplayFor(model => model.Name)
        </dd>
        <dt class = "col-sm-2">
            @Html.DisplayNameFor(model => model.City)
        </dt>
        <dd class = "col-sm-10">
            @Html.DisplayFor(model => model.City)
        </dd>
        <dt class = "col-sm-2">
            @Html.DisplayNameFor(model => model.Email)
        </dt>
        <dd class = "col-sm-10">
            @Html.DisplayFor(model => model.Email)
        </dd>
    </dl>
    
    <form asp-action="Delete">
        <input type="hidden" asp-for="Id" />
        <input type="submit" value="Delete" class="btn btn-danger" /> |
        <a asp-action="Index">Back to List</a>
    </form>
</div>

Details.cshtml

@model ImageUpload.Models.FirstStudent

@{
    ViewData["Title"] = "Details";
}

<h1>Details</h1>

<div>
    <h4>FirstStudent</h4>
    <hr />
    <dl class="row">
        <dt class = "col-sm-2">
            @Html.DisplayNameFor(model => model.Name)
        </dt>
        <dd class = "col-sm-10">
            @Html.DisplayFor(model => model.Name)
        </dd>
        <dt class = "col-sm-2">
            @Html.DisplayNameFor(model => model.City)
        </dt>
        <dd class = "col-sm-10">
            @Html.DisplayFor(model => model.City)
        </dd>
        <dt class = "col-sm-2">
            @Html.DisplayNameFor(model => model.Email)
        </dt>
        <dd class = "col-sm-10">
            @Html.DisplayFor(model => model.Email)
        </dd>
    </dl>
</div>
<div>
    <a asp-action="Edit" asp-route-id="@Model.Id">Edit</a> |
    <a asp-action="Index">Back to List</a>
</div>

Edit.cshtml

@model ImageUpload.Models.FirstStudent

@{
    ViewData["Title"] = "Edit";
}

<h1>Edit</h1>

<h4>FirstStudent</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Edit">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <input type="hidden" asp-for="Id" />
            <div class="form-group">
                <label asp-for="Name" class="control-label"></label>
                <input asp-for="Name" class="form-control" />
                <span asp-validation-for="Name" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="City" class="control-label"></label>
                <input asp-for="City" class="form-control" />
                <span asp-validation-for="City" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Email" class="control-label"></label>
                <input asp-for="Email" class="form-control" />
                <span asp-validation-for="Email" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Save" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>

Index.cshtml

@model IEnumerable<ImageUpload.Models.FirstStudent>

@{
    ViewData["Title"] = "Index";
}

<h1>Index</h1>

<p>
    <a asp-action="Create">Create New</a>
</p>
<table class="table">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.Name)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.City)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Email)
            </th>
            <th></th>
        </tr>
    </thead>
    <tbody>
@foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Name)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.City)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Email)
            </td>
            <td>
                <a asp-action="Edit" asp-route-id="@item.Id">Edit</a> |
                <a asp-action="Details" asp-route-id="@item.Id">Details</a> |
                <a asp-action="Delete" asp-route-id="@item.Id">Delete</a>
            </td>
        </tr>
}
    </tbody>
</table>

NotFound.cshtml

@model int
@{
    ViewData["Title"] = "NotFound";
}

<h1>NotFound</h1>
<div class="text-danger">Student Not Found = @Model Wrong</div>

Home

Create.cshtml

@model ImageUpload.ViewModel.StudentViewModel

@{
    ViewData["Title"] = "Create";
}

<h1>Create</h1>

<h4>StudentViewModel</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Create" enctype="multipart/form-data">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Name" class="control-label"></label>
                <input asp-for="Name" class="form-control" />
                <span asp-validation-for="Name" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="ProfileImage" class="control-label"></label>
                <input asp-for="ProfileImage" class="form-control" />
                <span asp-validation-for="ProfileImage" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>

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

Index.cshtml

@model IEnumerable<ImageUpload.Models.Student>

@{
    ViewData["Title"] = "Index";
}

<h1>Index</h1>

<p>
    <a asp-action="Create">Create New</a>
</p>
<table class="table">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.Name)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.ProfileImage)
            </th>
            <th></th>
        </tr>
    </thead>
    <tbody>
@foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Name)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.ProfileImage)
                <img src="~/Images/@item.ProfileImage" class="rounded-circle" width="=50" height="50" asp-append-version> 
            </td>
            <td>
                <a asp-action="Edit" asp-route-id="@item.Id">Edit</a> |
                <a asp-action="Details" asp-route-id="@item.Id">Details</a> |
                <a asp-action="Delete" asp-route-id="@item.Id">Delete</a>
            </td>
        </tr>
}
    </tbody>
</table>

Test

_index.cshtml[Partial View]

@model IEnumerable<ImageUpload.Models.Student>
@{
    ViewData["Title"] = "_index";
}

<h1>_index</h1>
@foreach (var item in Model)
{
    <div>
        @item.Id
    </div>
    <div>
        @item.Name
    </div>
}

Index.cshtml

@model IEnumerable<ImageUpload.Models.Student>
@{
    ViewData["Title"] = "Index";
}

<h1>Index</h1>
<partial name="_index"/>
@await Html.PartialAsync("_index",Model)


appsettings.json

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=CHETUIWK1048\\SQLDEV2019;Database=DisplayImage;Trusted_Connection=True;MultipleActiveResultSets=True"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

Startup.cs

using ImageUpload.Data;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ImageUpload
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                //it is added for wrong url error
                app.UseStatusCodePagesWithRedirects("/Error/{0}");
                app.UseExceptionHandler("/Home/Error");
            }
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}





Post a Comment

0 Comments