Article

File upload in asp.net core mvc

In this article we will learn how to File upload in asp.net core mvc?

In this blog we will see File upload in asp.net core MVC and save in to database.

Step 1. Open visual studio 2017 and select ASP.NET Core Web Application, and then will click on “OK” button.

Step 2. In this step we will select Empty and then will click on OK button.

Step 3. In this step we will create one folder with name “Model” and after that we will add one Student.cs class in this model folder.

Step 4. Please write this code on “Student.cs” page.
Key Point : Add this namespace “using System.ComponentModel.DataAnnotations”

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace Demo.Model
{
    public class Student
    {
        public int Id { get; set; }
        [Required, MaxLength(50, ErrorMessage = "Name cannot exceed 50 characters")]
        public string Name { get; set; }
        public string PhotoPath { get; set; }
    }
}

Step 5. We will create one class with name “AppDbContext” in model folder.

Step 6. Please write this code on “AppDbContext.cs” page.
Key Point : Add this namespace “using Microsoft.EntityFrameworkCore;”

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Demo.Model
{
    public class AppDbContext : DbContext
    {
        public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
        {

        }
        public DbSet<Student> Students { get; set; }
    }
}

Step 7. Please open “appsetting.json” file write this code for connect with Sql Server.

{
  "ConnectionStrings": {
    "StudentDBConnection": "Server=DESKTOP-3JHBTTU\\SQLEXPRESS;database=StudentDB;Trusted_Connection=true"
  },
  
    "Logging": {
      "LogLevel": {
        "Default": "Warning"
      }
    },
    "AllowedHosts": "*"
  }

Step 8. We will create one class with name “IStudentRepository” in model folder and write this code on “IStudentRepository.cs” page.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Demo.Model
{
    public interface IStudentRepository
    {
        Student Add(Student student);
    }
}

Step 9. We will create one class with name “MockStudentRepository” in model folder and we will write this code on this created MockStudentRepository.cs page.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Demo.Model
{
    public class MockStudentRepository : IStudentRepository
    {
        private readonly AppDbContext context;
        public MockStudentRepository(AppDbContext context)
        {
            this.context = context;
        }
        public Student Add(Student student)
        {
            context.Students.Add(student);
            context.SaveChanges();
            return student;
        }
    }
}

Step 10. Please open “Startup.cs” file and we will write this red mark code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Demo.Model;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace Demo
{
    public class Startup
    {
        
        private IConfiguration _config;
        public Startup(IConfiguration config)
        {
            _config = config;
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContextPool<AppDbContext>(
               options => options.UseSqlServer(_config.GetConnectionString("StudentDBConnection")));
            services.AddMvc().AddXmlSerializerFormatters();
           services.AddScoped<IStudentRepository, MockStudentRepository>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc(routes =>
            {
                routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

Step 11. We will create one ViewModel and after that create one class with name “StudentCreateViewModel” and we will write this code on this page.

Key Point:
IFormFile is in Microsoft.AspNetCore.Http namespace.
The file uploaded on the server we can be accessed through Model Binding using the IFormFile interface.

using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace Demo.ViewModel
{
    public class StudentCreateViewModel
    {
       
        [Required, MaxLength(50, ErrorMessage = "Name cannot exceed 50 characters")]
        public string Name { get; set; }
        public IFormFile PhotoPath { get; set; }
    }
}

Step 12. In this step we will create one new folder with name “Controllers” and add one HomeController.cs then finally we will add this code on HomeController.

Key Point :
If the Photo property on the incoming model object is not null, then the user has selected an image to upload.

using Demo.Model;
using Demo.ViewModel;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace Demo.Controllers
{
    public class HomeController : Controller
    {
        private readonly IStudentRepository _studentRepository;
        private readonly IHostingEnvironment hostingEnvironment;
        public HomeController(IStudentRepository studentRepository, IHostingEnvironment hostingEnviornment)
        {
            _studentRepository = studentRepository;
            this.hostingEnvironment = hostingEnviornment;
        }
        [HttpGet]
        public ViewResult Create()
        {

            return View();
        }

        [HttpPost]
        public IActionResult Create(StudentCreateViewModel model)
        {
            if (ModelState.IsValid)
            {
                string uniqueFileName = null;
                if (model.PhotoPath != null)
                {
                     // The image must be uploaded to the images folder in wwwroot
                    // To get the path of the wwwroot folder we are using the HostingEnvironment service provided by ASP.NET Core
                   
                    string uploadfolder = Path.Combine(hostingEnvironment.WebRootPath, "images");
                     // If you want to file name is unique then we are appending a new GUID value and and an underscore to the file name
                    uniqueFileName = Guid.NewGuid().ToString() + "_" + model.PhotoPath.FileName;
                    string filepath = Path.Combine(uploadfolder, uniqueFileName);
                     // Use CopyTo() method provided by IFormFile interface to
                    // copy the file to wwwroot/images folder
                    model.PhotoPath.CopyTo(new FileStream(filepath, FileMode.Create));
                }
                Student newStudent = new Student
                {
                    Name = model.Name,
                     // Store the file name in PhotoPath property of the student object
                    // which gets saved to the Students database table
                    PhotoPath = uniqueFileName
                };
                _studentRepository.Add(newStudent);
                
            }
            return View();
        }
    }
}

Step 13. In this step we will Add migration. Open Package manager console and write this command for Add-Migration then hit enter.

you can see here one Migrations folder have created.

Add-Migration InitialMigration
//Command for update database
Update-Database

Step 14. We will write this code on Create.cshtml page for File upload in asp.net core mvc .
Key Point :

i : To support file upload set the form element enctype=”multipart/form-data”
ii : asp-for tag helper is set to “Photo” property. “Photo” property type is IFormFile so at runtime asp.net core generates file upload control (input type=file)

@model Demo.ViewModel.StudentCreateViewModel
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@{
    ViewData["Title"] = "Create";
}
<script src="~/lib/twitter-bootstrap/bootstrap.min.js"></script>
<h1>Create</h1>



    <form enctype="multipart/form-data" asp-controller="Home" asp-action="Create" method="post" class="mt-3">
        <div class="form-group row">
            <label asp-for="Name"></label>
                <input asp-for="Name" class="form-control" placeholder="Name" />
                <span asp-validation-for="Name" class="text-danger"></span>
            </div>
        


        <div class="form-group row">
            <label asp-for="PhotoPath"></label>
           
                
                    <input asp-for="PhotoPath" id="photopathInput" />
                    <label class="custom-file-label" id="chooseFileLabel"></label>
                
          
        </div>


        <div class="form-group row">
            <div class="col-sm-10">
                <button type="submit" class="btn btn-primary">Create</button>
            </div>
        </div>

        <script>
            $(document).ready(function () {
                $("#photopathInput").on("change", function () {
                    var fileName = $(this).val().split("\\").pop();
                    $(this).next('#chooseFileLabel').html(fileName);
                });
            });


        </script>

    </form>



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

Output

Leave a Reply

Your email address will not be published. Required fields are marked *