Upload PDF Files Into DataBase In Binary Format Using ASP.NET MVC

Many time we need to work with files and most of the time developers prefer to store files on physical location of server which is very difficult because it will consume lots of memory of server , So in this article we will learn how to upload files in binary format into database using ASP.NET MVC  . So lets learn step by step so beginners also can also understand .
Step 1: Create an MVC Application.
Now, let us start with a step by step approach from the creation of a simple MVC Application in the following:
  1. "Start", followed by "All Programs" and select "Microsoft Visual Studio 2015".
  2. Click "File", followed by "New" and click "Project". Select "ASP.NET Web Application Template", provide the Project a name as you wish and click OK. After clicking, the following Window will appear:
Step 2: Create Model Class
Now, let us create the model class file, named EmpModel.cs, by right clicking on Models folder and define the following properties  as:
public class EmpModel  
   {  
       [Required]  
       [DataType(DataType.Upload)]  
       [Display(Name ="Select File")]  
       public HttpPostedFileBase files { get; set; }  
   }  
  
Step 3 : Create Table and Stored Procedure
Now Create the stored procedure and table to stored the uploaded files in binary format , Use the following script to create table named FileDetails as
CREATE TABLE [dbo].[FileDetails](  
    [Id] [int] IDENTITY(1,1) NOT NULL,  
    [FileName] [varchar](60) NULL,  
    [FileContent] [varbinary](max) NULL  
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]  

As mentioned in preceding table script we have created three columns Id is for to identify files unique key , FileName for to store uploaded file name and FileContent to store uploaded file contents in binary format .
Create the following Stored Procedure  to insert file details using the given script as

Create Procedure [dbo].[AddFileDetails]  
(  
@FileName varchar(60),  
@FileContent varBinary(Max)  
)  
as  
begin  
Set NoCount on  
Insert into FileDetails values(@FileName,@FileContent)   
End  

In preceding we have created tables and stored procedures , I hope same you have created ;
Step 4 : Add Controller Class
Now, let us add ASP.NET MVC controller, as shown in the screenshot, given below:

After clicking Add button, it will show the Window. Specify the Controller name as Home with suffix Controller. Now, let's modify the default code of Home controller . After modifying the code of Homecontroller class, the code will look like:
HomeController.cs
using FileUploadDownLoadInMVC.Models;  
using System;  
using System.Collections.Generic;  
using System.IO;  
using System.Linq;  
using System.Web;  
using System.Web.Mvc;  
using Dapper;  
using System.Configuration;  
using System.Data.SqlClient;  
using System.Data;  
  
namespace FileUploadDownLoadInMVC.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")  
            {  
                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  
            {  
  
                ViewBag.FileStatus = "Invalid file format.";  
                return View();  
  
            }  
             
        }  
         
        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);  
  
        }  
    }  
}  
The preceding code snippet explained everything to upload  PDF file into database , I hope you have followed the same .
 Step 5:  Create strongly typed View
Right click on View folder of the created Application and create  strongly typed view  for uploading files by choosing EmpModel.cs class , The code snippet of the view's is look like as following .
FileUpload.cshtml
@model FileUploadDownLoadInMVC.Models.EmpModel  
  
@{  
    ViewBag.Title = "www.compilemode.com";  
}  
  
@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>  
}  
  
<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, we have done all the coding.
Step 6 - Run the Application
After running the Application, the UI of the Application will look like as follows

Now select PDF file from your system and click Upload button. It will upload the file in the database table which details look like as follows


I hope, from the preceding examples, you have learned, how to upload PDF files in the binary format into the the database In ASP.NET MVC.
Note
  • This article used dapper ORM to interact with the database. Thus, you need to install dapper ORM into the Application. If you don't know how to install dapper ORM in MVC, watch the video, using the link, given below-
  • Its important to define enctype = "multipart/form-data" in form action, else the value will be null in the controller.
  • Makes changes in web.config file connectionstring tag, based on your database location and configuration.
  • Since this is a demo, it might not be using the proper standards. Thus, improve it, depending on your skills.
Summary
I hope, this article is useful for all the readers. If you have any suggestions, please contact me.

Post a Comment

www.CodeNirvana.in

Protected by Copyscape
Copyright © Compilemode