Skip to main content

File Uploading in C#

In this article of ASP.NET MVC we will learn about Validation File Uploading so Let's start.

Firstly create Model Class, In my case there are two classes like EmpModel and FileDetailsModel




EmpModel Class:


using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace File_Upload.Models
{
    public class EmpModel
    {
        [Required]
        [DataType(DataType.Upload)]
        [Display(Name = "Select File")]
        public byte files { get; set; }
    }
}




FileDetailsModel Class:


using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace File_Upload.Models
{
    public class FileDetailsModel
    {
        public int Id { get; set; }
        [Display(Name = "Uploaded File")]
        public String FileName { get; set; }
        public byte[] FileContent { get; set; }
    }
}




Then create Controller, in my case i have created HomeController but you can give any name ,its depend upon you.




using File_Upload.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Mvc;
using Dapper;

namespace File_Upload.Controllers
{
    public class HomeController : Controller
    {
       

        public ActionResult FileUpload()
        {
            return View();
        }

       
        [HttpPost]
        public ActionResult FileUpload(HttpPostedFileBase files)
        {

            String FileExt = Path.GetExtension(files.FileName).ToUpper();

           
                if (FileExt == ".PDF" || FileExt == ".xls")
                {
                    Stream str = files.InputStream;
                    BinaryReader Br = new BinaryReader(str);
                    Byte[] FileDet = Br.ReadBytes((Int32)str.Length);

                    FileDetailsModel Fd = new Models.FileDetailsModel();


               

                    Fd.FileName = files.FileName;
                    Fd.FileContent = FileDet;
                    SaveFileDetails(Fd);
                    return RedirectToAction("FileUpload");
               
                }
                else if (files.ContentLength > 3)
                {
                    ViewBag.length = "File size should be 3 kb";
                    return View();
                }
                else
                {

                    ViewBag.FileStatus = "Invalid file format.";
                    return View();

                }
            return View();
        }
          

       

 


        [HttpGet]
        public FileResult DownLoadFile(int id)
        {


            List<FileDetailsModel> ObjFiles = GetFileList();

            var FileById = (from FC in ObjFiles
                            where FC.Id.Equals(id)
                            select new { FC.FileName, FC.FileContent }).ToList().FirstOrDefault();

            return File(FileById.FileContent, "application/pdf", FileById.FileName);

        }

        [HttpGet]
        public PartialViewResult FileDetails()
        {
            List<FileDetailsModel> DetList = GetFileList();


            ViewBag.msg = "error";
            return PartialView("FileDetails", DetList);


        }
        private List<FileDetailsModel> GetFileList()
        {
            List<FileDetailsModel> DetList = new List<FileDetailsModel>();

            DbConnection();
            con.Open();

            DetList = SqlMapper.Query<FileDetailsModel>(con, "GetFileDetails", commandType: CommandType.StoredProcedure).ToList();


            con.Close();
            return DetList;
        }

        protected void Insertion(object sender, EventArgs e, HttpPostedFileBase files)
        {
           
            String FileExt = Path.GetExtension(files.FileName).ToUpper();


            if (FileExt == ".PDF" || FileExt == ".xls")
            {
                Stream str = files.InputStream;
                BinaryReader Br = new BinaryReader(str);
                Byte[] FileDet = Br.ReadBytes((Int32)str.Length);

                FileDetailsModel Fd = new Models.FileDetailsModel();




                Fd.FileName = files.FileName;
                Fd.FileContent = FileDet;
                SaveFileDetails(Fd);
              

            }
            else if (files.ContentLength > 3)
            {
                ViewBag.length = "File size should be 3 kb";
               
            }
            else
            {

                ViewBag.FileStatus = "Invalid file format.";
              

            }
        }
        private void SaveFileDetails(FileDetailsModel objDet)
        {

            DynamicParameters Parm = new DynamicParameters();
            Parm.Add("@FileName", objDet.FileName);
            Parm.Add("@FileContent", objDet.FileContent);
            DbConnection();
            con.Open();
            con.Execute("AddFileDetails", Parm, commandType: System.Data.CommandType.StoredProcedure);
            con.Close();


        }
    

     

        private SqlConnection con;
        private string constr;
        private void DbConnection()
        {
            constr = ConfigurationManager.ConnectionStrings["dbcon"].ToString();
            con = new SqlConnection(constr);

        }




    }



}


Now Let's create Views , there are two Views FileDetails.cshtml and FileUpload.cshtml

FileDetails.cshtml:


@model IEnumerable<File_Upload.Models.FileDetailsModel>
@{
    ViewBag.Title = "FileDetails";
}


<table class="table table-bordered table-responsive table-hover">
    <tr>
        <th class="col-md-4">
            @Html.DisplayNameFor(model => model.FileName)
        </th>

        <th class="col-md-2"></th>
    </tr>

    @foreach (var item in Model)
    {
        <tr>

            <td>
                @Html.DisplayFor(modelItem => item.Id)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.FileName)
            </td>

            <td>
                @Html.ActionLink("Download", "DownLoadFile", new { id = item.Id })

            </td>
        </tr>
    }

</table>

FileUpload.cshtml:



@model File_Upload.Models.EmpModel

@{
    ViewBag.Title = "FileUpload";
}

@using (Html.BeginForm("FileUpload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{

    @Html.AntiForgeryToken()

<div class="form-horizontal">
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.files, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.TextBoxFor(model => model.files, "", new { @type = "file", @multiple = "multiple" })
            @Html.ValidationMessageFor(model => model.files, "", new { @class = "text-danger" })
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Upload" class="btn btn-primary" />
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10 text-success">
            @ViewBag.FileStatus
        </div>
    </div>



    <div class="form-group">
        <div class="col-md-offset-2 col-md-10 text-success">
            @ViewBag.length
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-8">
            @Html.Action("FileDetails", "Home")

        </div>
    </div>
</div>
}

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







Now in the end make connection of sql server:
Goto Server Explorer in Visual Studio then Add Connection => Give a server name (Open Sql Server and copy Server Name and paste on Add Connection dialog box under Server Name)  => Select Database => Click Ok => Right Click on your connection and select Properties => On Bottom right you will see Connection String Label and its connection so copy connection then go to
Web.config file add a code:

<connectionStrings>
    <add name="dbcon" connectionString="Paste it here which you copy" providerName="System.Data.SqlClient"/>
   
  </connectionStrings>

In the end build your Solution ( Ctrl + Shift + B) and run your project.

Comments

Popular posts from this blog

CRUD Operation in ASP.NET MVC Using ADO.NET Jquery Ajax

In this article of ASP.NET MVC we will learn about CRUD operation using jquery ajax so let's start. Firstly open visual studio: Go to File => New and Select Project,when you select project then New Project Dialogbox will appear. Select ASP.NET Web Application (.NET Framework) and give a name to your project , as we are building CRUD Operation so our project's name could be CRUD_OPEATION and then select OK. Now you will see a new dialogbox, select Empty Template and MVC folder. After create project you will see a like screen like this: Now go to Models folder and add ADO.NET Entity Data Model and give any name like in my case i give dbEntities and selec OK: After that you will see a dilogbox called Entity Data Model Wizard, select EF Designer from database and select Next: After that a new dilogbox will appear and it will ask a new connection to your sql server, then select New Connection and give server name ( if you want to see your server name then open sql server,it will ...

Showing List of database Using Jquery, Ajax and Datatable

In this article of ASP.NET MVC we will learn about Showing List of database Using Jquery, Ajax and Datatable so let's start: Firstly create a model class which you want to show a list of datatable.In my case i create a model class namely called GEN_TaskMaster:  public class GEN_TaskMaster     {         public long sysTaskID { get; set; }         public long sysUserID { get; set; }                  public DateTime Task_Date { get; set; }         public string Task_Assign_To { get; set; }         public string Task_Assign_From { get; set; }         public string Task_Description { get; set; }                 } Then go to your controller and paste a code below: public ActionResult ListAll()         {             var list = db.Database...

ASP.NET MVC - Get Started

ASP.NET is a free web framework for building websites and web applications on .NET Framework using HTML, CSS, and JavaScript. These tutorials are designed for beginners and professionals who want to learn ASP.NET MVC 5. In the next article we will learn How to Create First Asp.net MVC application. Click Here To Create First MVC Application