Collecting image data or any other file format data is equally important as collecting textual data. Although collecting textual data is more simple than collecting an image or any other file format data, the choice for storing the image or any other file format data is the most difficult part, but, it entirely depends on one's business & system requirement.

Today, I shall be demonstrating uploading of the image file into the database on ASP.NET MVC5 platform. This article is not specific to image files only, you can use the provided solution with any type of file format as well.

ASP.NET MVC 5 - Upload Image/File Into Database

Before moving to the coding part, let us observe some of the advantages and disadvantages of uploading an image or any other file format data into the database.

Advantages (Pros)
  1. Sensitive images or any other file format data is fully secure as it is only accessible via system/software. Files are not accessible via links.
  2. Storing of the uploaded file is guaranteed.
  3. Images/Files store on database do not require extra backups.
  4. Transnational integrity is guaranteed as you won't be locked into typical reader/writer problem and deleting the entry in the database means the file is actually deleted, you do not need extra precautions to delete the file i.e. ensuring that file is deleted from both database and file system.
  5. Image replication is easy (if needed).
  6. In load-balanced web servers or distributed environments, dealing with synchronizing images across multiple file systems is difficult especially in a web application where a new server may be added any time.

Disadvantages (Cons)

  1. Database storage becomes expensive for many and large file storage.
  2. There will be a performance penalty as latency to retrieve image/file is slower and database lookup is slower than filesystem lookup.
  3. Additional code is needed to extract and stream files.
  4. You cannot directly edit the files, especially images files, as you can not directly utilize image edit features such as file resize and file cropping.
  5. There will be more load on the database.
  6. Web server bandwidth will increase which adds additional costs.

Prerequisites

Following are some prerequisites before you proceed any further in this tutorial:

  1. Knowledge of ASP.NET MVC5.
  2. Knowledge of HTML.
  3. Knowledge of Bootstrap.
  4. Knowledge of C# Programming.

You can download the complete source code for this tutorial or you can follow the step by step discussion below. The sample code is being developed in Microsoft Visual Studio 2015 Enterprise.

Let's begin now.

Step 1

First, create your SQL server database and name it "db_img". Then execute following script into your SQL server database i.e.

  1. USE [db_img]
  2. GO
  3. /****** Object: StoredProcedure [dbo].[sp_insert_file] Script Date: 11/18/2018 12:27:55 AM ******/
  4. DROP PROCEDURE [dbo].[sp_insert_file]
  5. GO
  6. /****** Object: StoredProcedure [dbo].[sp_get_file_details] Script Date: 11/18/2018 12:27:55 AM ******/
  7. DROP PROCEDURE [dbo].[sp_get_file_details]
  8. GO
  9. /****** Object: StoredProcedure [dbo].[sp_get_all_files] Script Date: 11/18/2018 12:27:55 AM ******/
  10. DROP PROCEDURE [dbo].[sp_get_all_files]
  11. GO
  12. /****** Object: Table [dbo].[tbl_file] Script Date: 11/18/2018 12:27:55 AM ******/
  13. DROP TABLE [dbo].[tbl_file]
  14. GO
  15. /****** Object: Table [dbo].[tbl_file] Script Date: 11/18/2018 12:27:55 AM ******/
  16. SET ANSI_NULLS ON
  17. GO
  18. SET QUOTED_IDENTIFIER ON
  19. GO
  20. CREATE TABLE [dbo].[tbl_file](
  21. [file_id] [int] IDENTITY(1,1) NOT NULL,
  22. [file_name] [nvarchar](max) NOT NULL,
  23. [file_ext] [nvarchar](max) NOT NULL,
  24. [file_base6] [nvarchar](max) NOT NULL,
  25. CONSTRAINT [PK_tbl_file] PRIMARY KEY CLUSTERED
  26. (
  27. [file_id] ASC
  28. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
  29. ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
  30. GO
  31. /****** Object: StoredProcedure [dbo].[sp_get_all_files] Script Date: 11/18/2018 12:27:55 AM ******/
  32. SET ANSI_NULLS ON
  33. GO
  34. SET QUOTED_IDENTIFIER ON
  35. GO
  36. -- =============================================
  37. -- Author: <Author,,Name>
  38. -- Create date: <Create Date,,>
  39. -- Description: <Description,,>
  40. -- =============================================
  41. CREATE PROCEDURE [dbo].[sp_get_all_files]
  42. AS
  43. BEGIN
  44. /****** Script for SelectTopNRows command from SSMS ******/
  45. SELECT [file_id]
  46. ,[file_name]
  47. ,[file_ext]
  48. FROM [db_img].[dbo].[tbl_file]
  49. END
  50. GO
  51. /****** Object: StoredProcedure [dbo].[sp_get_file_details] Script Date: 11/18/2018 12:27:55 AM ******/
  52. SET ANSI_NULLS ON
  53. GO
  54. SET QUOTED_IDENTIFIER ON
  55. GO
  56. -- =============================================
  57. -- Author: <Author,,Name>
  58. -- Create date: <Create Date,,>
  59. -- Description: <Description,,>
  60. -- =============================================
  61. CREATE PROCEDURE [dbo].[sp_get_file_details]
  62. @file_id INT
  63. AS
  64. BEGIN
  65. /****** Script for SelectTopNRows command from SSMS ******/
  66. SELECT [file_id]
  67. ,[file_name]
  68. ,[file_ext]
  69. ,[file_base6]
  70. FROM [db_img].[dbo].[tbl_file]
  71. WHERE [tbl_file].[file_id] = @file_id
  72. END
  73. GO
  74. /****** Object: StoredProcedure [dbo].[sp_insert_file] Script Date: 11/18/2018 12:27:55 AM ******/
  75. SET ANSI_NULLS ON
  76. GO
  77. SET QUOTED_IDENTIFIER ON
  78. GO
  79. -- =============================================
  80. -- Author: <Author,,Name>
  81. -- Create date: <Create Date,,>
  82. -- Description: <Description,,>
  83. -- =============================================
  84. CREATE PROCEDURE [dbo].[sp_insert_file]
  85. @file_name NVARCHAR(MAX),
  86. @file_ext NVARCHAR(MAX),
  87. @file_base64 NVARCHAR(MAX)
  88. AS
  89. BEGIN
  90. /****** Script for SelectTopNRows command from SSMS ******/
  91. INSERT INTO [dbo].[tbl_file]
  92. ([file_name]
  93. ,[file_ext]
  94. ,[file_base6])
  95. VALUES
  96. (@file_name
  97. ,@file_ext
  98. ,@file_base64)
  99. END
  100. GO

Step 2

Create a new MVC web project and name it "ImgSaveDb".

Step 3

Open the "Views->Shared->_Layout.cshtml" file and replace following code in it i.e.:

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>@ViewBag.Title</title>
  7. @Styles.Render("~/Content/css")
  8. @Scripts.Render("~/bundles/modernizr")
  9. <!-- Font Awesome -->
  10. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" />
  11. </head>
  12. <body>
  13. <div class="navbar navbar-inverse navbar-fixed-top">
  14. <div class="container">
  15. <div class="navbar-header">
  16. <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
  17. <span class="icon-bar"></span>
  18. <span class="icon-bar"></span>
  19. <span class="icon-bar"></span>
  20. </button>
  21. </div>
  22. </div>
  23. </div>
  24. <div class="container body-content">
  25. @RenderBody()
  26. <hr />
  27. <footer>
  28. <center>
  29. <p><strong>Copyright © @DateTime.Now.Year - <a href="http://wwww.asmak9.com/">Asma's Blog</a>.</strong> All rights reserved.</p>
  30. </center>
  31. </footer>
  32. </div>
  33. @*Scripts*@
  34. @Scripts.Render("~/bundles/jquery")
  35. @Scripts.Render("~/bundles/jqueryval")
  36. @Scripts.Render("~/bundles/bootstrap")
  37. @RenderSection("scripts", required: false)
  38. </body>
  39. </html>

In the above code, I have simply created a basic default layout page and linked the required libraries into it.

Step 4

Create a new "Helper_Code\Objects\ImgObj.cs" file and replace the following code in it i.e.:

  1. //-----------------------------------------------------------------------
  2. // <copyright file="ImgObj.cs" company="None">
  3. // Copyright (c) Allow to distribute this code and utilize this code for personal or commercial purpose.
  4. // </copyright>
  5. // <author>Asma Khalid</author>
  6. //-----------------------------------------------------------------------
  7. namespace ImgSaveDb.Helper_Code.Objects
  8. {
  9. using System;
  10. using System.Collections.Generic;
  11. using System.Linq;
  12. using System.Web;
  13. /// <summary>
  14. /// Image object class.
  15. /// </summary>
  16. public class ImgObj
  17. {
  18. #region Properties
  19. /// <summary>
  20. /// Gets or sets Image ID.
  21. /// </summary>
  22. public int FileId { get; set; }
  23. /// <summary>
  24. /// Gets or sets Image name.
  25. /// </summary>
  26. public string FileName { get; set; }
  27. /// <summary>
  28. /// Gets or sets Image extension.
  29. /// </summary>
  30. public string FileContentType { get; set; }
  31. #endregion
  32. }
  33. }

In the above code, I have simply created an object class which will map my image file metadata from SQL database.

Step 5

Now, create a new "Models\ImgViewModel.cs" file and replace the following code in it i.e.:

  1. //-----------------------------------------------------------------------
  2. // <copyright file="ImgViewModel.cs" company="None">
  3. // Copyright (c) Allow to distribute this code and utilize this code for personal or commercial purpose.
  4. // </copyright>
  5. // <author>Asma Khalid</author>
  6. //-----------------------------------------------------------------------
  7. namespace ImgSaveDb.Models
  8. {
  9. using System.Collections.Generic;
  10. using System.ComponentModel.DataAnnotations;
  11. using System.Web;
  12. using Helper_Code.Objects;
  13. /// <summary>
  14. /// Image view model class.
  15. /// </summary>
  16. public class ImgViewModel
  17. {
  18. #region Properties
  19. /// <summary>
  20. /// Gets or sets Image file.
  21. /// </summary>
  22. [Required]
  23. [Display(Name = "Upload File")]
  24. public HttpPostedFileBase FileAttach { get; set; }
  25. /// <summary>
  26. /// Gets or sets Image file list.
  27. /// </summary>
  28. public List<ImgObj> ImgLst { get; set; }
  29. #endregion
  30. }
  31. }

In the above code, I have created my view model which I will attach with my view. Here, I have created a HttpPostedFileBase type file attachment property which will capture uploaded image/file data from the end-user and image object type list property which will display a list of images that I have stored in my database.

Step 6

Create a new "Controllers\ImgController.cs" file and replace the following code in it i.e.

  1. //-----------------------------------------------------------------------
  2. // <copyright file="ImgController.cs" company="None">
  3. // Copyright (c) Allow to distribute this code and utilize this code for personal or commercial purpose.
  4. // </copyright>
  5. // <author>Asma Khalid</author>
  6. //-----------------------------------------------------------------------
  7. namespace ImgSaveDb.Controllers
  8. {
  9. using System;
  10. using System.Collections.Generic;
  11. using System.Linq;
  12. using System.Web;
  13. using System.Web.Mvc;
  14. using Helper_Code.Objects;
  15. using Models;
  16. /// <summary>
  17. /// Image controller class.
  18. /// </summary>
  19. public class ImgController : Controller
  20. {
  21. #region Private Properties
  22. /// <summary>
  23. /// Gets or sets database manager property.
  24. /// </summary>
  25. private db_imgEntities databaseManager = new db_imgEntities();
  26. #endregion
  27. #region Index view method.
  28. #region Get: /Img/Index method.
  29. /// <summary>
  30. /// Get: /Img/Index method.
  31. /// </summary>
  32. /// <returns>Return index view</returns>
  33. public ActionResult Index()
  34. {
  35. // Initialization.
  36. ImgViewModel model = new ImgViewModel { FileAttach = null, ImgLst = new List<ImgObj>() };
  37. try
  38. {
  39. // Settings.
  40. model.ImgLst = this.databaseManager.sp_get_all_files().Select(p => new ImgObj
  41. {
  42. FileId = p.file_id,
  43. FileName = p.file_name,
  44. FileContentType = p.file_ext
  45. }).ToList();
  46. }
  47. catch (Exception ex)
  48. {
  49. // Info
  50. Console.Write(ex);
  51. }
  52. // Info.
  53. return this.View(model);
  54. }
  55. #endregion
  56. #region POST: /Img/Index
  57. /// <summary>
  58. /// POST: /Img/Index
  59. /// </summary>
  60. /// <param name="model">Model parameter</param>
  61. /// <returns>Return - Response information</returns>
  62. [HttpPost]
  63. [AllowAnonymous]
  64. [ValidateAntiForgeryToken]
  65. public ActionResult Index(ImgViewModel model)
  66. {
  67. // Initialization.
  68. string fileContent = string.Empty;
  69. string fileContentType = string.Empty;
  70. try
  71. {
  72. // Verification
  73. if (ModelState.IsValid)
  74. {
  75. // Converting to bytes.
  76. byte[] uploadedFile = new byte[model.FileAttach.InputStream.Length];
  77. model.FileAttach.InputStream.Read(uploadedFile, 0, uploadedFile.Length);
  78. // Initialization.
  79. fileContent = Convert.ToBase64String(uploadedFile);
  80. fileContentType = model.FileAttach.ContentType;
  81. // Saving info.
  82. this.databaseManager.sp_insert_file(model.FileAttach.FileName, fileContentType, fileContent);
  83. }
  84. // Settings.
  85. model.ImgLst = this.databaseManager.sp_get_all_files().Select(p => new ImgObj
  86. {
  87. FileId = p.file_id,
  88. FileName = p.file_name,
  89. FileContentType = p.file_ext
  90. }).ToList();
  91. }
  92. catch (Exception ex)
  93. {
  94. // Info
  95. Console.Write(ex);
  96. }
  97. // Info
  98. return this.View(model);
  99. }
  100. #endregion
  101. #endregion
  102. #region Download file methods
  103. #region GET: /Img/DownloadFile
  104. /// <summary>
  105. /// GET: /Img/DownloadFile
  106. /// </summary>
  107. /// <param name="fileId">File Id parameter</param>
  108. /// <returns>Return download file</returns>
  109. public ActionResult DownloadFile(int fileId)
  110. {
  111. // Model binding.
  112. ImgViewModel model = new ImgViewModel { FileAttach = null, ImgLst = new List<ImgObj>() };
  113. try
  114. {
  115. // Loading dile info.
  116. var fileInfo = this.databaseManager.sp_get_file_details(fileId).First();
  117. // Info.
  118. return this.GetFile(fileInfo.file_base6, fileInfo.file_ext);
  119. }
  120. catch (Exception ex)
  121. {
  122. // Info
  123. Console.Write(ex);
  124. }
  125. // Info.
  126. return this.View(model);
  127. }
  128. #endregion
  129. #endregion
  130. #region Helpers
  131. #region Get file method.
  132. /// <summary>
  133. /// Get file method.
  134. /// </summary>
  135. /// <param name="fileContent">File content parameter.</param>
  136. /// <param name="fileContentType">File content type parameter</param>
  137. /// <returns>Returns - File.</returns>
  138. private FileResult GetFile(string fileContent, string fileContentType)
  139. {
  140. // Initialization.
  141. FileResult file = null;
  142. try
  143. {
  144. // Get file.
  145. byte[] byteContent = Convert.FromBase64String(fileContent);
  146. file = this.File(byteContent, fileContentType);
  147. }
  148. catch (Exception ex)
  149. {
  150. // Info.
  151. throw ex;
  152. }
  153. // info.
  154. return file;
  155. }
  156. #endregion
  157. #endregion
  158. }
  159. }

In the above code, I have created a databaseManager private property which will allow me to access my SQL database via entity framework. Then, I have created "GetFile(...)" helper method which will convert my SQL database stored image file from base64 data format to byte data format. Then, I have created "DownloadFile(...)" method which will return image file stored in the SQL database base on the provided image file ID. Then, I have created GET "Index(...)" method which will retrieve the list of images data from SQL database and send it to the view page. Finally, I have created POST() "Index(...)" method which will receive the input image file from the end-user, then convert that file into a base64 data format and finally save the base64 data format file into the SQL database.

Step 7

Now, create a view "Views\Img\Index.cshtml" file and replace the following code in it i.e.

  1. @using ImgSaveDb.Models
  2. @model ImgSaveDb.Models.ImgViewModel
  3. @{
  4. ViewBag.Title = "ASP.NET MVC5: Upload Image into Database";
  5. }
  6. <div class="row">
  7. <div class="panel-heading">
  8. <div class="col-md-8">
  9. <h3>
  10. <i class="fa fa-file-text-o"></i>
  11. <span>ASP.NET MVC5: Upload Image into Database</span>
  12. </h3>
  13. </div>
  14. </div>
  15. </div>
  16. <br/>
  17. <div class="row">
  18. <div class="col-md-6 col-md-push-2">
  19. <section>
  20. @using (Html.BeginForm("Index", "Img", FormMethod.Post, new { enctype = "multipart/form-data", @class = "form-horizontal", role = "form" }))
  21. {
  22. @Html.AntiForgeryToken()
  23. <div class="well bs-component">
  24. <br />
  25. <div class="row">
  26. <div class="col-md-12">
  27. <div class="col-md-8 col-md-push-2">
  28. <div class="input-group">
  29. <span class="input-group-btn">
  30. <span class="btn btn-default btn-file">
  31. Browse…
  32. @Html.TextBoxFor(m => m.FileAttach, new { type = "file", placeholder = Html.DisplayNameFor(m => m.FileAttach), @class = "form-control" })
  33. </span>
  34. </span>
  35. <input type="text" class="form-control" readonly>
  36. </div>
  37. @Html.ValidationMessageFor(m => m.FileAttach, "", new { @class = "text-danger custom-danger" })
  38. </div>
  39. </div>
  40. </div>
  41. <div class="form-group">
  42. <div class="col-md-12">
  43. </div>
  44. </div>
  45. <div class="form-group">
  46. <div class="col-md-offset-5 col-md-10">
  47. <input type="submit" class="btn btn-danger" value="Upload" />
  48. </div>
  49. </div>
  50. </div>
  51. }
  52. </section>
  53. </div>
  54. </div>
  55. <hr />
  56. <div class="row">
  57. <div class="col-md-offset-4 col-md-8">
  58. <h3>List of Imagess </h3>
  59. </div>
  60. </div>
  61. <hr />
  62. @if (Model.ImgLst != null &&
  63. Model.ImgLst.Count > 0)
  64. {
  65. <div class="row">
  66. <div class="col-md-offset-1 col-md-8">
  67. <section>
  68. <table class="table table-bordered table-striped">
  69. <thead>
  70. <tr>
  71. <th style="text-align: center;">Sr.</th>
  72. <th style="text-align: center;">Image Name</th>
  73. <th style="text-align: center;"></th>
  74. </tr>
  75. </thead>
  76. <tbody>
  77. @for (int i = 0; i < Model.ImgLst.Count; i++)
  78. {
  79. <tr>
  80. <td style="text-align: center;">@(i + 1)</td>
  81. <td style="text-align: center;">
  82. <div class="input-group" style="height:40px;">
  83. <i class="fa fa-2x fa-paperclip text-navy"></i>
  84. <a class="download-file1" href="@Url.Action("DownloadFile", "Img", new { fileId = @Model.ImgLst[i].FileId })" target="_blank">
  85. @Model.ImgLst[i].FileName
  86. </a>
  87. </div>
  88. </td>
  89. <td style="text-align: center;">
  90. <div>
  91. <img src="@Url.Action("DownloadFile", "Img", new { fileId = @Model.ImgLst[i].FileId })" width="100" height="100" />
  92. </div>
  93. </td>
  94. </tr>
  95. }
  96. </tbody>
  97. </table>
  98. </section>
  99. </div>
  100. </div>
  101. }
  102. @section Scripts
  103. {
  104. @*Scripts*@
  105. @Scripts.Render("~/bundles/bootstrap-file")
  106. @*Styles*@
  107. @Styles.Render("~/Content/Bootstrap-file/css")
  108. }

In the above code, I have created a simple view for uploading an image file to the server for storing it into the SQL database and then display the uploaded image files list. I have created bootstrap style file upload control and a table to display the list of uploaded images on the server in the SQL database.

Step 8

Now, execute the project and you will be able to see the following in action i.e.:

ASP.NET MVC 5 - Upload Image/File Into Database

ASP.NET MVC 5 - Upload Image/File Into Database

ASP.NET MVC 5 - Upload Image/File Into Database

Conclusion

In this article, you learned about uploading of the image file into the database on ASP.NET MVC5 platform. You also learned how to convert the image file into the base64 data format. You also learned to convert base64 data format to byte data format. You also learned to retrieve image data stored in SQL server database as base64 and you learned about the advantages & disadvantages of storing image/file into the database.