Upload Files in Database using dot net core

In this article I’ll discuss how to upload single and multiple files in sql server database using dot net core 3.1 and C#. This article will focus more on elaborating how a save file in folder and related description in database.

I have used VS 2019

Open visual studio 2019

Click on Create New Project then window will open

 

Select Asp.net Core Web Application and click on Next Button then window will be open

Here specify

Name              -> Name of Project you want

Location          -> Select/Specify Location where you want to create Project.

Solution Name            ->Solution Name will be same as Project Name

Click on Create Button then window will open as-

Here Select Web Application (Model-View-Controller) and uncheck Configure for Https

And Click on Create Button your project will be created.

Process to Connect with Sql Server database

Add below Packages using Nuget package manager

Microsoft.EntityFrameworkCore.SqlServer

Microsoft.EntityFrameworkCore.Design

Microsoft.EntityFrameworkCore.Tools

Right Click on Project -> Click on Manage NuGet Packages

Window will open then click on Browse tab and in search tab type above package and click on install then popup window will open then click on Accept button then your packages will be install on your project as -

Create Table in Sql server Database

CREATE TABLE [dbo].[UploadFileDetail](
       [Id] [varchar](200) NOT NULL,
       [FileName] [varchar](50) NULL,
       [Extension] [varchar](10) NULL,
       [FilePath] [varchar](200) NULL,
       [PostId] [int] NULL,
       [C_Date] [datetime] NULL,
 CONSTRAINT [PK_UploadFileDetail] PRIMARY KEY CLUSTERED
( [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]    
) ON [PRIMARY]

 

Type below Command to Create ContextClass of all Tables Created on Database

Scaffold-DbContext "Server=DESKTOP-I6QIQ9N;Database=MVC_Test_DB;Trusted_Connection=True;User Id=sa;Password=Shashi;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Context "MVCTestDBContext"

Type below Command to Create ContextClass of single/specific Tables Created on Database and press Enter

Scaffold-DbContext "server=DESKTOP-I6QIQ9N;user=sa;password=Shashi;database=EINVOICE" Microsoft.EntityFrameworkCore.SqlServer -OutputDir DBModel -Context "EinvoiceContext" -Tables UploadFileDetail

After adding Context Class Folder will be create in Solution Explorer

Also Context class as well as database table class will be created on Folder.
In Context Class Connection automatically Created you can check –
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
  {
     if (!optionsBuilder.IsConfigured)
      {
          optionsBuilder.UseSqlServer("server=DESKTOP-I6QIQ9N;user id=sa;password=Shashi;database=EINVOICE;");
      }
  }
 

Create Model class in Models Folder with Name FileUploadModel

 public class FileUploadModel
        {
            EinvoiceContext db = new EinvoiceContext();
            public string Id { get; set; }
            public string FileName { get; set; }
            public string Extension { get; set; }
            public string FilePath { get; set; }
            public int? PostId { get; set; }
            public DateTime? CDate { get; set; }
            public List<IFormFile> files { get; set; }


            public List<FileUploadModel> GetFile_Details(string searchval)
            {

                var Filelist = db.UploadFileDetail.AsEnumerable().Select(s =>
                     new FileUploadModel()
                     {
                         Id = s.Id,
                         FileName = s.FileName,
                         Extension = s.Extension,
                         FilePath = s.FilePath,
                         PostId = s.PostId,
                         CDate = s.CDate
                     });
                return Filelist.ToList();
            }
        }

 

Add Empty Controller with Name UploadFiles and Write code as bellow -

 public class UploadFilesController : Controller
    {
        public IActionResult Index(string searchString)
        {
            FileUploadModel bl = new FileUploadModel();
            List<FileUploadModel> lst = new List<FileUploadModel>();
            lst = bl.GetFile_Details(searchString);
            return View(lst);
        }

        public IActionResult UploadNewFiles()
        {
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> UploadNewFiles(FileUploadModel FUmodel)
        {
            EinvoiceContext db = new EinvoiceContext();
            UploadFileDetail Pobj = new UploadFileDetail();
            List<UploadFileDetail> fileDetails = new List<UploadFileDetail>();
            for (int i = 0; i < FUmodel.files.Count; i++)
            {
                UploadFileDetail objupf = new UploadFileDetail();
                var file = FUmodel.files[i];

                if (file != null && file.Length > 0)
                {
                    var uploadsRootFolder = Path.Combine(Directory.GetCurrentDirectory(), "DocumentsFiles");
                    if (!Directory.Exists(uploadsRootFolder))
                    {
                        Directory.CreateDirectory(uploadsRootFolder);
                    }

                    var fileName = Path.GetFileName(file.FileName);
                    objupf.FileName = fileName;
                    objupf.Extension = Path.GetExtension(fileName);
                    objupf.Id = Convert.ToString(Guid.NewGuid());
                    objupf.CDate = System.DateTime.Now;
                    // var path = Path.Combine(HttpContext.Current.Server.MapPath("~/BlogUploadFiles/"), objupf.Id + objupf.Extension);
                    var path = Path.Combine(Directory.GetCurrentDirectory(), "DocumentsFiles", objupf.Id + objupf.Extension);

                    using (var stream = new FileStream(path, FileMode.Create))
                    {
                        await file.CopyToAsync(stream);
                    }

                    objupf.FilePath = path;
                    fileDetails.Add(objupf);
                    db.UploadFileDetail.Add(objupf);
                    db.SaveChanges();
                }
            }

            return RedirectToAction("Index");
        }

        public FileResult Download(String p, String d)
        {
            var path = Path.Combine(Directory.GetCurrentDirectory(), "DocumentsFiles", p);
            var fs = new FileStream(path, FileMode.Open);

            return File(fs, "application/octet-stream", d);

        }

        [HttpPost]
        public JsonResult DeleteFile(string id)
        {
            EinvoiceContext db = new EinvoiceContext();
            if (String.IsNullOrEmpty(id))
            {
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return Json(new { Result = "Error" });
            }
            try
            {
                // Guid guid = new Guid(id);
                UploadFileDetail fileDetail = db.UploadFileDetail.Find(id);
                if (fileDetail == null)
                {
                    Response.StatusCode = (int)HttpStatusCode.NotFound;
                    return Json(new { Result = "Error" });
                }

                //Remove from database
                db.UploadFileDetail.Remove(fileDetail);
                db.SaveChanges();

                //Delete file from the file system
                var path = Path.Combine(Directory.GetCurrentDirectory(), "DocumentsFiles", fileDetail.Id + fileDetail.Extension);
                if (System.IO.File.Exists(path))
                {
                    System.IO.File.Delete(path);
                }
                return Json(new { Result = "OK" });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "ERROR", Message = ex.Message });
            }
        }
    }

Right Click on Index()  and UploadNewFiles() Method and click on Add View then View will be Added. 

Index View Design Page

 

@model IEnumerable<FileUploadModel>
@{
    ViewData["Title"] = "Index";
}

<div class="content-wrapper">
    <section class="content">
        <div class="row">
            <div class="col-xs-12">
                <div class="box">

                    <div class="box-header with-border">
                        <h3 class="box-title">@Html.ActionLink("Upload New Files", "UploadNewFiles")</h3>
                        <div class="box-tools pull-right">
                        </div>
                    </div>

                    <!-- /.box-header -->
                    <div class="box-body" style="overflow:auto;">
                        @using (Html.BeginForm("Index", "UploadFiles", FormMethod.Get))
                        {
                            <p>
                                Search : @Html.TextBox("SearchString", ViewBag.CurrentFilter as string)
                                <input type="submit" value="Search" />
                            </p>
                        }
                        <br />
                        <table id="example1" class="table table-bordered table-striped">
                            <thead>
                                <tr style="color:red">
                                    <th>
                                        @Html.Label("Id", ViewBag.CurrentFilter as string)
                                    </th>
                                    <th>
                                        @Html.Label("File Name", ViewBag.CurrentFilter as string)
                                    </th>
                                    <th>
                                        @Html.Label("Extension", ViewBag.CurrentFilter as string)
                                    </th>
                                    <th>
                                        @Html.Label("Upload Date", ViewBag.CurrentFilter as string)
                                    </th>
                                    <th>
                                        @Html.Label("Action", ViewBag.CurrentFilter as string)
                                    </th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach (var item in Model)
                                {
                                    <tr>
                                        <td>
                                            @Html.DisplayFor(modelItem => item.Id)
                                        </td>
                                        <td>
                                            @Html.DisplayFor(modelItem => item.FileName)
                                        </td>
                                        <td>
                                            @Html.DisplayFor(modelItem => item.Extension)
                                        </td>
                                        <td>
                                            @Html.DisplayFor(modelItem => item.CDate)
                                        </td>

                                        <td>
                                            <a class="title" href="/UploadFiles/Download/?p=@(item.Id + item.Extension)&d=@item.FileName">@item.FileName</a> |
                                            <a href="javascript:void(0);" data-id="@item.Id" class="deleteItem">Delete</a>

                                        </td>
                                    </tr>
                                }

                            </tbody>
                        </table>
                    </div>
                    <!-- /.box-body -->
                </div>
                <!-- /.box -->
            </div>
            <!-- /.col -->
        </div>
        <!-- /.row -->
    </section>

</div>

<script src="~/Scripts/jquery-1.10.2.min.js"></script>

<script>
        $('.deleteItem').click(function (e) {
            e.preventDefault();
            var $ctrl = $(this);
            if (confirm('Do you really want to delete this file?')) {
                $.ajax({
                    url: '@Url.Action("DeleteFile")',
                    type: 'POST',
                    data: { id: $(this).data('id') }
                }).done(function (data) {
                    if (data.Result == "OK") {
                        $ctrl.closest('li').remove();
                    }
                    else if (data.Result.Message) {
                        alert(data.Result.Message);
                    }
                }).fail(function () {
                    alert("There is something wrong. Please try again.");
                })

            }
        });
</script>


UploadNewFiles  Design Page

@model FileUploadModel

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

<div class="content-wrapper">

    @using (Html.BeginForm("UploadNewFiles", "UploadFiles", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        <section class="content">
            <div class="row">
                <div class="col-xs-12">
                    <div class="box">

                        <div class="box-header with-border">
                            <h3 class="box-title">
                            </h3>
                            <div class="box-tools pull-right">
                            </div>
                        </div>
                        <div class="box-body">
                            <div class="form-row">
                                <div class="form-group col-md-12">
                                    <label for="inputEmail4">Files:</label>
                                    <input type="file" name="files" multiple="multiple" />
                                </div>
                            </div>

                            <button type="submit" class="btn btn-primary">Save</button>
                        </div>
                    </div>
                </div>
            </div>
        </section>
    }

</div>

Result will show as -

Leave a Comment