Downloading Files From DataBase in ASP.NET MVC

This article explains step-by-step how to download the files in ASP.NET MVC from a database which is stored in a binary format. So let's learn step-by-step so beginners can also understand.

Step 1 : View Binary formatted Uploaded Files

Step 2: Create an ASP.NET MVC Application.

Now, let us create a simple MVC application to download the uploaded  file as:
  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 3:
Create Model Class

Now, let us create the model class file, named FileDetailsModel.cs, by right clicking on Models folder and define the following properties  as:
public class FileDetailsModel  
       public int Id { get; set; }  
       [Display(Name = "Uploaded File")]  
       public String FileName { get; set; }  
       public byte[] FileContent { get; set; }  
Step 4 : Create Stored Procedure

Now Create the stored procedure to view the uploaded files using following script as
CREATE Procedure [dbo].[GetFileDetails]  
@Id int=null  
select Id,FileName,FileContent from FileDetails  
where Id=isnull(@Id,Id)  
 I hope same you have created ;

Step 5 : Add Controller Class

Now, let us add ASP.NET MVC controller, as shown in the screenshot, given below:

After clicking the "Add" button, it will show the window. Specify the controller name as "Home" with the suffix "ControllerNow, let's modify the default code of the Home Controller. After modifying the code of the Homecontroller class, the code will look like this:

    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 FileUploadDownLoadInMVC.Models;  
    using System.Data;  
    namespace FileUploadDownLoadInMVC.Controllers  
        public class HomeController : Controller  
            #region Upload Download file  
            public ActionResult Index()  
                return View();  
            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);  
            #region View Uploaded files  
            public PartialViewResult FileDetails()  
                List<FileDetailsModel> DetList = GetFileList();  
                return PartialView("FileDetails", DetList);  
            private List<FileDetailsModel> GetFileList()  
                List<FileDetailsModel> DetList = new List<FileDetailsModel>();  
                DetList = SqlMapper.Query<FileDetailsModel>(con, "GetFileDetails", commandType: CommandType.StoredProcedure).ToList();  
                return DetList;  
            #region Database connection  
            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 6:  Create View

Right click on View folder of the created Application and create view named Index and Partial view FileDetails , The code snippet of the view's is look like as following .

    ViewBag.Title = "";  
@using (Html.BeginForm())  
        <div class="form-group">  
            <div class="col-md-offset-2 col-md-10 text-success">  
        <div class="form-group">  
            <div class="col-md-8">  
                @Html.Action("FileDetails", "Home")  
<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>  
@model IEnumerable<FileUploadDownLoadInMVC.Models.FileDetailsModel>  
<table class="table table-bordered">  
        <th class="col-md-4">  
            @Html.DisplayNameFor(model => model.FileName)  
        <th class="col-md-2"></th>  
@foreach (var item in Model) {  
            @Html.DisplayFor(modelItem => item.FileName)  
            @Html.ActionLink("Downlaod", "DownLoadFile", new { id=item.Id })   
Now, we have done all the coding.

Step 7 - Run the Application

After running the application, the UI of the application will look like as follows.

Now click on download button , then it will shows the following popup

Choose to open or save the file , I have chosen to open the files , the contents of the files will be look like as follows

I hope, from the preceding examples, you have learned how to download binary-formatted PDF files from a database.

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

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

I hope this article is useful for all the readers. If you have any suggestions, please contact me.

Read related article
Don't Forget To 

    Post a Comment

    Protected by Copyscape
    Copyright © Compilemode