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-
- "Start", followed by "All Programs" and select "Microsoft Visual Studio 2015".
- 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 in EmpModel.cs class and FileDetailsModel as:
The code snippet of EmpModel.cs and FileDetailsModel .cs will look like-
- public class EmpModel
- {
- [Required]
- [DataType(DataType.Upload)]
- [Display(Name ="Select File")]
- public HttpPostedFileBase files { get; set; }
- }
- public class FileDetailsModel
- {
- public int Id { get; set; }
- [Display(Name = "Uploaded File")]
- public String FileName { get; set; }
- public byte[] FileContent { get; set; }
- }
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-
- CREATE TABLE [dbo].[FileDetails](
- [Id] [int] IDENTITY(1,1) NOT NULL,
- [FileName] [varchar](60) NULL,
- [FileContent] [varbinary](max) NULL
- ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
Create the stored procedure to insert the file details, using the script, given below-
- Create Procedure [dbo].[AddFileDetails]
- (
- @FileName varchar(60),
- @FileContent varBinary(Max)
- )
- as
- begin
- Set NoCount on
- Insert into FileDetails values(@FileName,@FileContent)
- End
To get the uploaded file details, use the code, given below-
- CREATE Procedure [dbo].[GetFileDetails]
- (
- @Id int=null
- )
- as
- begin
- select Id,FileName,FileContent from FileDetails
- where Id=isnull(@Id,Id)
- 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-
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
- 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
- {
- #region Upload Download file
- 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();
- }
- }
- [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);
- }
- #endregion
- #region View Uploaded files
- [HttpGet]
- public PartialViewResult FileDetails()
- {
- List<FileDetailsModel> DetList = GetFileList();
- 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;
- }
- #endregion
- #region Database related operations
- 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();
- }
- #endregion
- #region Database connection
- private SqlConnection con;
- private string constr;
- private void DbConnection()
- {
- constr =ConfigurationManager.ConnectionStrings["dbcon"].ToString();
- con = new SqlConnection(constr);
- }
- #endregion
- }
- }

YANGA NTULIPosted Jul 19, 2021, 10:18 AM
Thanks a lot, it works 100%
Vithal WadjePosted Sep 7, 2016, 4:58 AM
Thanks
Avinash ThakurPosted Sep 6, 2016, 11:36 PM
Nice Article sir