In this article I will explain with an example, how to upload files, save (insert) file to database Table, retrieve (display) files and download the files from Database Table using Entity Framework in ASP.Net MVC.
Note: For beginners in ASP.Net MVC and Entity Framework, please refer my article ASP.Net MVC: Simple Entity Framework Tutorial with example. It covers all the information needed for connecting and configuring Entity Framework.
 
 

Database

This article makes use of a table named tblFiles whose schema is defined as follows.
Entity Framework: Upload Files, Save (Insert) to database, Retrieve (Display) and Download Files from database in ASP.Net MVC
 
Note: You can download the database table SQL by clicking the download link below.
          Download SQL file
 
 

Entity Framework Model

Once the Entity Framework is configured and connected to the database table, the Model will look as shown below.
Entity Framework: Upload Files, Save (Insert) to database, Retrieve (Display) and Download Files from database in ASP.Net MVC
 
 

Namespaces

You will need to import the following namespace.
using System.IO;
 
 

Controller

The Controller consists of following Action methods.

Action method for handling GET operation

Inside this Action method, file records are fetched from the database using Entity Framework and returned to the View.
 

Action method for handling POST operation for uploading Files

This Action method gets called when a File is selected and the Upload Button is clicked which accepts the HttpPostedFileBase as parameter.
Note: In case the HttpPostedFileBase parameter is appearing NULL, please refer the article ASP.Net MVC: HttpPostedFileBase always returns NULL.
 
The uploaded file is converted to BYTE Array using BinaryReader class and finally, is inserted into the database table using Entity Framework.
After successful insertion of the File, RedirectToAction is called which redirects to the Index Action method.
 

Action method for handling POST operation for downloading Files

When the Download Link inside the HTML Table (Grid) is clicked, the Id of the particular file is sent to this Action method and using the File ID, the File’s binary data is fetched from the database using Entity Framework.
Finally, the File is downloaded using the File function which accepts the Binary data, Content Type and Name of the file.
public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        FilesEntities entities = new FilesEntities();
        return View(entities.tblFiles.ToList());
    }
 
    [HttpPost]
    public ActionResult Index(HttpPostedFileBase postedFile)
    {
        byte[] bytes;
        using (BinaryReader br = new BinaryReader(postedFile.InputStream))
        {
            bytes = br.ReadBytes(postedFile.ContentLength);
        }
        FilesEntities entities = new FilesEntities();
        entities.tblFiles.Add(new tblFile
        {
            Name = Path.GetFileName(postedFile.FileName),
            ContentType = postedFile.ContentType,
            Data = bytes
        });
        entities.SaveChanges();
        return RedirectToAction("Index");
    }
 
    [HttpPost]
    public FileResult DownloadFile(int? fileId)
    {
        FilesEntities entities = new FilesEntities();
        tblFile file = entities.tblFiles.ToList().Find(p => p.id == fileId.Value);
        return File(file.Data, file.ContentType, file.Name);
    }
}
 
 

View

HTML Markup

Inside the View, in the very first line the Entity Model class is declared as IEnumerable which specifies that it will be available as a Collection.
The View consists of two HTML Forms which have been created using the Html.BeginForm method with the following parameters.
ActionName – Name of the Action.
ControllerName – Name of the Controller. In this case the name is Home.
FormMethod – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
Inside the View, following script file is inherited.
1. jquery.min.js
 

Uploading the File

This Form has been specified with enctype=“multipart/form-data” attribute as it is necessary for File Upload operation.
The Form consists of an HTML FileUpload element and a Submit Button.
When the Submit Button is clicked, the Index Action method for handling POST operation will be called.
 

Downloading the File

The Form consists of an HTML HiddenField element and a Hidden Submit Button.
When any Download Link inside the HTML Table (Grid) is clicked, then the DownloadFile JavaScript function is called, which sets the FileId into the HiddenField which ultimately submits the Form.
When the Form is submitted, the DownloadFile Action method is called, which performs the File download operation.
 

Displaying the Files

For displaying the files, an HTML Table is used. A FOR EACH loop will be executed over the Model which will generate the HTML Table rows with the File records.
@model IEnumerable<Save_Files_Database_EF_MVC.tblFile>
 
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    @using (Html.BeginForm("Index""Home"FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        <input type="file" name="postedFile"/>
        <input type="submit" id="btnUpload" value="Upload"/>
    }
    @using (Html.BeginForm("DownloadFile""Home"FormMethod.Post))
    {
        <input type="hidden" id="hfFileId" name="FileId"/>
        <input type="submit" id="btnDownload" value="Download" style="display:none"/>
    }
    <hr/>
    <table cellpadding="0" cellspacing="0">
        <tr>
            <th style="width:50px">File ID</th>
            <th style="width:120px">File Name</th>
            <th style="width:80px">Download</th>
        </tr>
        @if (Model.Count() > 0)
        {
            foreach (var file in Model)
            {
                <tr>
                    <td>@file.id</td>
                    <td>@file.Name</td>
                    <td><href="javascript:;" onclick="DownloadFile(@file.id)">Download</a></td>
                </tr>
            }
        }
        else
        {
            <tr>
                <td colspan="3">&nbsp;</td>
            </tr>
        }
    </table>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <script type="text/javascript">
        function DownloadFile(fileId) {
            $("#hfFileId").val(fileId);
            $("#btnDownload")[0].click();
        };
    </script>
</body>
</html>
 
 

Screenshot

Entity Framework: Upload Files, Save (Insert) to database, Retrieve (Display) and Download Files from database in ASP.Net MVC
 
 

Downloads