Uploading Downloading PDF Files In Binary Format Using FileResult In ASP.NET MVC

Background
 
Many times, we need to work with the file and storing the physical files on the Server, which is very difficult because it will consume lots of memory of the Server. Thus, in this article, we will learn, how to upload the files in the binary format into the database and download from the database with the help of ASP.NET MVC, using FileResult. Thus, let's learn step by step so the beginners can also understand.
 
Step 1 - Create 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,

    empty

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 in EmpModel.cs class and FileDetailsModel as:
 
The code snippet of EmpModel.cs and FileDetailsModel .cs will look like-
  1. public class EmpModel  
  2.    {  
  3.        [Required]  
  4.        [DataType(DataType.Upload)]  
  5.        [Display(Name ="Select File")]  
  6.        public HttpPostedFileBase files { getset; }  
  7.    }  
  8.   
  9.    public class FileDetailsModel  
  10.    {  
  11.        public int Id { getset; }  
  12.        [Display(Name = "Uploaded File")]  
  13.        public String FileName { getset; }  
  14.        public byte[] FileContent { getset; }  
  15.   
  16.   
  17.    } 
Step 3 - Create Table and Stored Procedure
 
Now, create the stored procedure and the table to store the uploaded files in binary format and display back to the user's view. Use the script, given below, to create the table named FileDetails as-
  1. CREATE TABLE [dbo].[FileDetails](  
  2.     [Id] [int] IDENTITY(1,1) NOT NULL,  
  3.     [FileName] [varchar](60) NULL,  
  4.     [FileContent] [varbinary](maxNULL  
  5. ON [PRIMARY] TEXTIMAGE_ON [PRIMARY
As mentioned in the preceding table script, we have created three columns Id, which is to identify the files unique key. FileName to store uploaded file name and FileContent to store the uploaded file contents in the binary format.
 
Create the stored procedure to insert the file details, using the script, given below-
 
  1. Create Procedure [dbo].[AddFileDetails]  
  2. (  
  3. @FileName varchar(60),  
  4. @FileContent varBinary(Max)  
  5. )  
  6. as  
  7. begin  
  8. Set NoCount on  
  9. Insert into FileDetails values(@FileName,@FileContent)  
  10.   
  11. End 
To get the uploaded file details, use the code, given below-
  1. CREATE Procedure [dbo].[GetFileDetails]  
  2. (  
  3. @Id int=null  
  4.   
  5.   
  6. )  
  7. as  
  8. begin  
  9.   
  10. select Id,FileName,FileContent from FileDetails  
  11. where Id=isnull(@Id,Id)  
  12. End 
We have created the tables and stored procedures. I hope, you have created the same.
 
Step 4 - Add Controller Class
 
Now, let us add ASP.NET MVC controller, as shown in the screenshot, given below-

empty 
 
After clicking Add button, it will show in 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
  1. using FileUploadDownLoadInMVC.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.IO;  
  5. using System.Linq;  
  6. using System.Web;  
  7. using System.Web.Mvc;  
  8. using Dapper;  
  9. using System.Configuration;  
  10. using System.Data.SqlClient;  
  11. using System.Data;  
  12.   
  13. namespace FileUploadDownLoadInMVC.Controllers  
  14. {  
  15.     public class HomeController : Controller  
  16.     {  
  17.          
  18.         #region Upload Download file  
  19.         public ActionResult FileUpload()  
  20.         {  
  21.             return View();  
  22.         }  
  23.   
  24.          
  25.         [HttpPost]  
  26.         public ActionResult FileUpload(HttpPostedFileBase files)  
  27.         {  
  28.   
  29.          String FileExt=Path.GetExtension(files.FileName).ToUpper();  
  30.   
  31.             if (FileExt == ".PDF")  
  32.             {  
  33.                 Stream str = files.InputStream;  
  34.                 BinaryReader Br = new BinaryReader(str);  
  35.                 Byte[] FileDet = Br.ReadBytes((Int32)str.Length);  
  36.   
  37.                 FileDetailsModel Fd = new Models.FileDetailsModel();  
  38.                 Fd.FileName = files.FileName;  
  39.                 Fd.FileContent = FileDet;  
  40.                 SaveFileDetails(Fd);  
  41.                 return RedirectToAction("FileUpload");  
  42.             }  
  43.             else  
  44.             {  
  45.   
  46.                 ViewBag.FileStatus = "Invalid file format.";  
  47.                 return View();  
  48.   
  49.             }  
  50.              
  51.         }  
  52.          
  53.         [HttpGet]  
  54.         public FileResult DownLoadFile(int id)  
  55.         {  
  56.   
  57.   
  58.             List<FileDetailsModel> ObjFiles = GetFileList();  
  59.   
  60.             var FileById = (from FC in ObjFiles  
  61.                             where FC.Id.Equals(id)  
  62.                             select new { FC.FileName, FC.FileContent }).ToList().FirstOrDefault();  
  63.   
  64.             return File(FileById.FileContent, "application/pdf", FileById.FileName);  
  65.   
  66.         }  
  67.         #endregion  
  68.  
  69.         #region View Uploaded files  
  70.         [HttpGet]  
  71.         public PartialViewResult FileDetails()  
  72.         {  
  73.             List<FileDetailsModel> DetList = GetFileList();  
  74.   
  75.             return PartialView("FileDetails", DetList);  
  76.   
  77.   
  78.         }  
  79.         private List<FileDetailsModel> GetFileList()  
  80.         {  
  81.             List<FileDetailsModel> DetList = new List<FileDetailsModel>();  
  82.   
  83.             DbConnection();  
  84.             con.Open();  
  85.             DetList = SqlMapper.Query<FileDetailsModel>(con, "GetFileDetails", commandType: CommandType.StoredProcedure).ToList();  
  86.             con.Close();  
  87.             return DetList;  
  88.         }  
  89.  
  90.         #endregion  
  91.  
  92.         #region Database related operations  
  93.         private void SaveFileDetails(FileDetailsModel objDet)  
  94.         {  
  95.   
  96.             DynamicParameters Parm = new DynamicParameters();  
  97.             Parm.Add("@FileName", objDet.FileName);  
  98.             Parm.Add("@FileContent", objDet.FileContent);  
  99.             DbConnection();  
  100.             con.Open();  
  101.             con.Execute("AddFileDetails", Parm, commandType: System.Data.CommandType.StoredProcedure);  
  102.             con.Close();  
  103.   
  104.   
  105.         }  
  106.         #endregion  
  107.  
  108.         #region Database connection  
  109.   
  110.         private SqlConnection con;  
  111.         private string constr;  
  112.         private void DbConnection()  
  113.         {  
  114.              constr =ConfigurationManager.ConnectionStrings["dbcon"].ToString();  
  115.              con = new SqlConnection(constr);  
  116.   
  117.         }  
  118.         #endregion  
  119.     }  
  120. }   
The preceding code snippet explained everything to upload and download PDF files from the 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 two strongly typed views; one is to upload the files by choosing EmpModel.cs class  and Partial View by choosing FileDetailsModel class to display the uploaded files. The code snippet of the view looks like-

FileUpload.cshtml 
  1. @model FileUploadDownLoadInMVC.Models.EmpModel  
  2.   
  3. @{  
  4.     ViewBag.Title = "www.compilemode.com";  
  5. }  
  6.   
  7. @using (Html.BeginForm("FileUpload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))  
  8. {  
  9.   
  10.     @Html.AntiForgeryToken()  
  11.   
  12.     <div class="form-horizontal">  
  13.         <hr />  
  14.         @Html.ValidationSummary(true, "", new { @class = "text-danger" })  
  15.         <div class="form-group">  
  16.             @Html.LabelFor(model => model.files, htmlAttributes: new { @class = "control-label col-md-2" })  
  17.             <div class="col-md-10">  
  18.                 @Html.TextBoxFor(model => model.files, "", new { @type = "file", @multiple = "multiple" })  
  19.                 @Html.ValidationMessageFor(model => model.files, "", new { @class = "text-danger" })  
  20.             </div>  
  21.         </div>  
  22.         <div class="form-group">  
  23.             <div class="col-md-offset-2 col-md-10">  
  24.                 <input type="submit" value="Upload" class="btn btn-primary" />  
  25.             </div>  
  26.         </div>  
  27.         <div class="form-group">  
  28.             <div class="col-md-offset-2 col-md-10 text-success">  
  29.                 @ViewBag.FileStatus  
  30.             </div>  
  31.         </div>  
  32.   
  33.         <div class="form-group">  
  34.             <div class="col-md-8">  
  35.                 @Html.Action("FileDetails", "Home")  
  36.   
  37.             </div>  
  38.         </div>  
  39.     </div>  
  40. }  
  41.   
  42. <script src="~/Scripts/jquery-1.10.2.min.js"></script>  
  43. <script src="~/Scripts/jquery.validate.min.js"></script>  
  44. <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script> 
FileDetails.cshtml
  1. @model IEnumerable<FileUploadDownLoadInMVC.Models.FileDetailsModel>  
  2.   
  3.   
  4. <table class="table table-bordered">  
  5.     <tr>  
  6.         <th class="col-md-4">  
  7.             @Html.DisplayNameFor(model => model.FileName)  
  8.         </th>  
  9.           
  10.         <th class="col-md-2"></th>  
  11.     </tr>  
  12.   
  13. @foreach (var item in Model) {  
  14.     <tr>  
  15.         <td>  
  16.             @Html.DisplayFor(modelItem => item.FileName)  
  17.         </td>  
  18.           
  19.         <td>  
  20.             @Html.ActionLink("Downlaod""DownLoadFile"new { id=item.Id })   
  21.              
  22.         </td>  
  23.     </tr>  
  24. }  
  25.   
  26. </table>   
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 and display back to the view is as follows-
 
 
Now, see the image, given below, of the table, which shows how the preceding uploaded file data is stored as-
 
 
From the preceding image, its clear that our uploaded file is stored into the database in the binary format. Now, click download button and it will show the following popup as-
 
 
Now, choose, whether to open the file or save the file according to your convenience. After opening the file, it will show the following contents, based on the uploaded file as-
 
 

I hope, from the preceding examples, you have learned, how to upload and download PDF files in the binary format from the database In ASP.NET MVC, using FileResult.
 
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.

  • Download the zip file of the sample Application for a better understanding.

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

Read more articles on ASP.NET,