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 ...

SignIn_SignUp in Asp.net Mvc

Models: SignUp Class: using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Web; namespace Signin_Signup.Models {     [Table("tbl_account")]     public class SignUp     {         public int id { get; set; }         public string name { get; set; }         public string email { get; set; }         public string password { get; set; }     } } DB Class: using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Web; namespace Signin_Signup.Models {     public class db:DbContext     {         public DbSet<SignUp> signups { get; set; }     } } User Controller: using Signin_Signup.Models; using System; using System.Collections.Generic; using System.L...

ASP.NET MVC Folder and File Structure

When we create an ASP.NET MVC 5 application, the Visual Studio by default creates the following folders and files for our application. App_Data App_Data folder can contain application data files like LocalDB, .mdf files, xml files and other data related files. App_Start: The App_Start folder of an MVC application is used to contain the class files which are needed to be executed at the time of application starts. The classes like BundleConfig, FilterConfig, RouteConfig, IdentityConfig, etc are stored within this folder. So in the simple word we can say that configuration related class files are stored here.  We will discuss the use of each of these class files in detail in our upcoming articles. Content Content folder contain static files like css, images and icons and MVC 5 application includes bootstrap.min.css, bootstrap.css and site.css by default. Controller Controller folder contain class file. It handles user request and response....