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; }

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. as  
  6. begin  
  7.   
  8. select Id,FileName,FileContent from FileDetails  
  9. where Id=isnull(@Id,Id)  
  10. 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.         [HttpPost]  
  24.         public ActionResult FileUpload(HttpPostedFileBase files)  
  25.         {  
  26.   
  27.          String FileExt=Path.GetExtension(files.FileName).ToUpper();  
  28.   
  29.             if (FileExt == ".PDF")  
  30.             {  
  31.                 Stream str = files.InputStream;  
  32.                 BinaryReader Br = new BinaryReader(str);  
  33.                 Byte[] FileDet = Br.ReadBytes((Int32)str.Length);  
  34.   
  35.                 FileDetailsModel Fd = new Models.FileDetailsModel();  
  36.                 Fd.FileName = files.FileName;  
  37.                 Fd.FileContent = FileDet;  
  38.                 SaveFileDetails(Fd);  
  39.                 return RedirectToAction("FileUpload");  
  40.             }  
  41.             else  
  42.             {  
  43.   
  44.                 ViewBag.FileStatus = "Invalid file format.";  
  45.                 return View();  
  46.   
  47.             }  
  48.              
  49.         }  
  50.          
  51.         [HttpGet]  
  52.         public FileResult DownLoadFile(int id)  
  53.         {
  54.             List<FileDetailsModel> ObjFiles = GetFileList();  
  55.   
  56.             var FileById = (from FC in ObjFiles  
  57.                             where FC.Id.Equals(id)  
  58.                             select new { FC.FileName, FC.FileContent }).ToList().FirstOrDefault();  
  59.   
  60.             return File(FileById.FileContent, "application/pdf", FileById.FileName);  
  61.   
  62.         }  
  63.         #endregion  
  64.  
  65.         #region View Uploaded files  
  66.         [HttpGet]  
  67.         public PartialViewResult FileDetails()  
  68.         {  
  69.             List<FileDetailsModel> DetList = GetFileList();  
  70.   
  71.             return PartialView("FileDetails", DetList);  
  72.         }  
  73.         private List<FileDetailsModel> GetFileList()  
  74.         {  
  75.             List<FileDetailsModel> DetList = new List<FileDetailsModel>();  
  76.   
  77.             DbConnection();  
  78.             con.Open();  
  79.             DetList = SqlMapper.Query<FileDetailsModel>(con, "GetFileDetails", commandType: CommandType.StoredProcedure).ToList();  
  80.             con.Close();  
  81.             return DetList;  
  82.         }  
  83.  
  84.         #endregion  
  85.  
  86.         #region Database related operations  
  87.         private void SaveFileDetails(FileDetailsModel objDet)  
  88.         {  
  89.   
  90.             DynamicParameters Parm = new DynamicParameters();  
  91.             Parm.Add("@FileName", objDet.FileName);  
  92.             Parm.Add("@FileContent", objDet.FileContent);  
  93.             DbConnection();  
  94.             con.Open();  
  95.             con.Execute("AddFileDetails", Parm, commandType: System.Data.CommandType.StoredProcedure);  
  96.             con.Close();
  97.         }  
  98.         #endregion  
  99.  
  100.         #region Database connection  
  101.   
  102.         private SqlConnection con;  
  103.         private string constr;  
  104.         private void DbConnection()  
  105.         {  
  106.              constr =ConfigurationManager.ConnectionStrings["dbcon"].ToString();  
  107.              con = new SqlConnection(constr);  
  108.   
  109.         }  
  110.         #endregion  
  111.     }  
  112. }   
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. <table class="table table-bordered">  
  3.     <tr>  
  4.         <th class="col-md-4">  
  5.             @Html.DisplayNameFor(model => model.FileName)  
  6.         </th>  
  7.           
  8.         <th class="col-md-2"></th>  
  9.     </tr>  
  10.   
  11. @foreach (var item in Model) {  
  12.     <tr>  
  13.         <td>  
  14.             @Html.DisplayFor(modelItem => item.FileName)  
  15.         </td>  
  16.           
  17.         <td>  
  18.             @Html.ActionLink("Downlaod""DownLoadFile"new { id=item.Id })   
  19.              
  20.         </td>  
  21.     </tr>  
  22. }  
  23.   
  24. </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,


Similar Articles