Uploading image or any type of file format in whether a file or into a database is always a topic of debate and confusion. Both the choices come with their set of advantages and disadvantages without a doubt. But, the ultimate decision entirely depends on the business requirement, resource costing, and availability.

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

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 as a file.

Advantages (Pros)

  1. Storage capacity is not expensive as third-party file cloud storage servers can be utilized which may or may not charge an additional cost to meet your requirement.
  2. No additional code is needed to access the uploaded file.
  3. The performance to retrieve image/file via file path is much faster as compared to the decoding of base 64 code back to the image from the database.
  4. The image file can be directly edited via available jQuery plugins, such as - cropping and resizing tools for the image file.
  5. The database will have less load on it which improves the costing plans.
  6. The Web Server bandwidth is more likely not to be increased and the costing plan will be further improved.

Disadvantages (Cons)

  1. Sensitive images or any other file format data is not fully secured even when you use third-party cloud storage like Amazon S3 as a link to the file is always public in order to get accessed. So, if the unauthorized user somehow gets access to the direct link of the file, then, he/she can easily download it.
  2. Storing of uploaded files are not guaranteed in a sense that file link is broken/lost or file is not uploaded but a link is available.
  3. Extra backups of the files are required along with the backup of the database where file paths are stored.
  4. File integrity is not guaranteed because the developer might forget to delete the actual file and only delete the file link from the database. This enables not only consistency issue especially in the distributed environment with many replication servers, but, also threatens end-user privacy & trust in a sense that user is under the impression that his/her file is deleted as the system shows but, in reality, only the link is deleted and actual file exist on the system, which means that targeted organization can illegally use end-user files for any sort of activity without the end-user consent. So, there is no way for end-user to know if it's an actual unintentional bug in the system or intentional scam from the targeted organization to collect user file data. Remember Facebook image deletion scandal back in 2009 for reference (Facebook reference is used for only education/understanding purpose without the intention of harming the reputation of the organization).
  5. Dealing with file and path synchronization in a distributed environment is difficult especially with multiple replication servers for backup.

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 as "db_img". Then, execute the following script into your SQL Server database.

  1. USE [db_img]
  2. GO
  3. /****** Object: StoredProcedure [dbo].[sp_insert_file] Script Date: 11/19/2018 8:11:10 AM ******/
  4. DROP PROCEDURE [dbo].[sp_insert_file]
  5. GO
  6. /****** Object: StoredProcedure [dbo].[sp_get_file_details] Script Date: 11/19/2018 8:11:10 AM ******/
  7. DROP PROCEDURE [dbo].[sp_get_file_details]
  8. GO
  9. /****** Object: StoredProcedure [dbo].[sp_get_all_files] Script Date: 11/19/2018 8:11:10 AM ******/
  10. DROP PROCEDURE [dbo].[sp_get_all_files]
  11. GO
  12. /****** Object: Table [dbo].[tbl_file] Script Date: 11/19/2018 8:11:10 AM ******/
  13. DROP TABLE [dbo].[tbl_file]
  14. GO
  15. /****** Object: Table [dbo].[tbl_file] Script Date: 11/19/2018 8:11:10 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_path] [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/19/2018 8:11:10 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/19/2018 8:11:10 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_path]
  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/19/2018 8:11:10 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_path 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_path])
  95. VALUES
  96. (@file_name
  97. ,@file_ext
  98. ,@file_path)
  99. END
  100. GO

Step 2

Create a new MVC web project and name it as "MVCImageSaveFile".

Step 3

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

  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 require libraries into it.

Step 4

Create a new "Helper_Code\Objects\ImgObj.cs" file and paste the following code in it.

  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 MVCImageSaveFile.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 put the following code in that.

  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 MVCImageSaveFile.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 HttpPostedFileBase type file attachment property which will capture the uploaded image/file data from the end-user and image object type list property which will display the list of images that I have stored as a file on my server and stored their file paths in my database.

Step 6

Create a new "Controllers\ImgController.cs" file and add the following code.

  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 MVCImageSaveFile.Controllers
  8. {
  9. using System;
  10. using System.Collections.Generic;
  11. using System.IO;
  12. using System.Linq;
  13. using System.Web;
  14. using System.Web.Mvc;
  15. using Helper_Code.Objects;
  16. using Models;
  17. /// <summary>
  18. /// Image controller class.
  19. /// </summary>
  20. public class ImgController : Controller
  21. {
  22. #region Private Properties
  23. /// <summary>
  24. /// Gets or sets database manager property.
  25. /// </summary>
  26. private db_imgEntities databaseManager = new db_imgEntities();
  27. #endregion
  28. #region Index view method.
  29. #region Get: /Img/Index method.
  30. /// <summary>
  31. /// Get: /Img/Index method.
  32. /// </summary>
  33. /// <returns>Return index view</returns>
  34. public ActionResult Index()
  35. {
  36. // Initialization.
  37. ImgViewModel model = new ImgViewModel { FileAttach = null, ImgLst = new List<ImgObj>() };
  38. try
  39. {
  40. // Settings.
  41. model.ImgLst = this.databaseManager.sp_get_all_files().Select(p => new ImgObj
  42. {
  43. FileId = p.file_id,
  44. FileName = p.file_name,
  45. FileContentType = p.file_ext
  46. }).ToList();
  47. }
  48. catch (Exception ex)
  49. {
  50. // Info
  51. Console.Write(ex);
  52. }
  53. // Info.
  54. return this.View(model);
  55. }
  56. #endregion
  57. #region POST: /Img/Index
  58. /// <summary>
  59. /// POST: /Img/Index
  60. /// </summary>
  61. /// <param name="model">Model parameter</param>
  62. /// <returns>Return - Response information</returns>
  63. [HttpPost]
  64. [AllowAnonymous]
  65. [ValidateAntiForgeryToken]
  66. public ActionResult Index(ImgViewModel model)
  67. {
  68. // Initialization.
  69. string filePath = string.Empty;
  70. string fileContentType = string.Empty;
  71. try
  72. {
  73. // Verification
  74. if (ModelState.IsValid)
  75. {
  76. // Converting to bytes.
  77. byte[] uploadedFile = new byte[model.FileAttach.InputStream.Length];
  78. model.FileAttach.InputStream.Read(uploadedFile, 0, uploadedFile.Length);
  79. // Initialization.
  80. fileContentType = model.FileAttach.ContentType;
  81. string folderPath = "~/Content/upload_files/";
  82. this.WriteBytesToFile(this.Server.MapPath(folderPath), uploadedFile, model.FileAttach.FileName);
  83. filePath = folderPath + model.FileAttach.FileName;
  84. // Saving info.
  85. this.databaseManager.sp_insert_file(model.FileAttach.FileName, fileContentType, filePath);
  86. }
  87. // Settings.
  88. model.ImgLst = this.databaseManager.sp_get_all_files().Select(p => new ImgObj
  89. {
  90. FileId = p.file_id,
  91. FileName = p.file_name,
  92. FileContentType = p.file_ext
  93. }).ToList();
  94. }
  95. catch (Exception ex)
  96. {
  97. // Info
  98. Console.Write(ex);
  99. }
  100. // Info
  101. return this.View(model);
  102. }
  103. #endregion
  104. #endregion
  105. #region Download file methods
  106. #region GET: /Img/DownloadFile
  107. /// <summary>
  108. /// GET: /Img/DownloadFile
  109. /// </summary>
  110. /// <param name="fileId">File Id parameter</param>
  111. /// <returns>Return download file</returns>
  112. public ActionResult DownloadFile(int fileId)
  113. {
  114. // Model binding.
  115. ImgViewModel model = new ImgViewModel { FileAttach = null, ImgLst = new List<ImgObj>() };
  116. try
  117. {
  118. // Loading dile info.
  119. var fileInfo = this.databaseManager.sp_get_file_details(fileId).First();
  120. // Info.
  121. return this.GetFile(fileInfo.file_path);
  122. }
  123. catch (Exception ex)
  124. {
  125. // Info
  126. Console.Write(ex);
  127. }
  128. // Info.
  129. return this.View(model);
  130. }
  131. #endregion
  132. #endregion
  133. #region Helpers
  134. #region Get file method.
  135. /// <summary>
  136. /// Get file method.
  137. /// </summary>
  138. /// <param name="filePath">File path parameter.</param>
  139. /// <returns>Returns - File.</returns>
  140. private FileResult GetFile(string filePath)
  141. {
  142. // Initialization.
  143. FileResult file = null;
  144. try
  145. {
  146. // Initialization.
  147. string contentType = MimeMapping.GetMimeMapping(filePath);
  148. // Get file.
  149. file = this.File(filePath, contentType);
  150. }
  151. catch (Exception ex)
  152. {
  153. // Info.
  154. throw ex;
  155. }
  156. // info.
  157. return file;
  158. }
  159. #endregion
  160. #region Write to file
  161. /// <summary>
  162. /// Write content to file.
  163. /// </summary>
  164. /// <param name="rootFolderPath">Root folder path parameter</param>
  165. /// <param name="fileBytes">File bytes parameter</param>
  166. /// <param name="filename">File name parameter</param>
  167. private void WriteBytesToFile(string rootFolderPath, byte[] fileBytes, string filename)
  168. {
  169. try
  170. {
  171. // Verification.
  172. if (!Directory.Exists(rootFolderPath))
  173. {
  174. // Initialization.
  175. string fullFolderPath = rootFolderPath;
  176. // Settings.
  177. string folderPath = new Uri(fullFolderPath).LocalPath;
  178. // Create.
  179. Directory.CreateDirectory(folderPath);
  180. }
  181. // Initialization.
  182. string fullFilePath = rootFolderPath + filename;
  183. // Create.
  184. FileStream fs = System.IO.File.Create(fullFilePath);
  185. // Close.
  186. fs.Flush();
  187. fs.Dispose();
  188. fs.Close();
  189. // Write Stream.
  190. BinaryWriter sw = new BinaryWriter(new FileStream(fullFilePath, FileMode.Create, FileAccess.Write));
  191. // Write to file.
  192. sw.Write(fileBytes);
  193. // Closing.
  194. sw.Flush();
  195. sw.Dispose();
  196. sw.Close();
  197. }
  198. catch (Exception ex)
  199. {
  200. // Info.
  201. throw ex;
  202. }
  203. }
  204. #endregion
  205. #endregion
  206. }
  207. }

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 a "GetFile(...)" helper method which will return the image file from my server base on the image file path stored in my SQL database.
  • I have also created the "WriteBytesToFile(...)" helper method which will store an uploaded file into my server provided file content path, which, in my case, is "~/Content/upload_files/".
  • Then, I have created "DownloadFile(...)" method which will return image file stored in the SQL database base on the provided image file ID.
  • I have created GET "Index(...)" method which will retrieve the list of images metadata from SQL database and send it to the View page.
  • Finally, I have created a POST "Index(...)" method which will receive the input image file from the end-user, then store that image file into my server at "~/Content/upload_files/" file location as a file using "WriteBytesToFile(...)" helper method. Then, it will store the file metadata and the file path into the SQL database.

Step 7

Now, create a View "Views\Img\Index.cshtml" file and add the following code.

  1. @using MVCImageSaveFile.Models
  2. @model MVCImageSaveFile.Models.ImgViewModel
  3. @{
  4. ViewBag.Title = "ASP.NET MVC5: Upload Image as File";
  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 as File</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 and to store the file path into the SQL database and then display the list of uploaded image files. I have created a bootstrap style file upload control and a table to display the list of uploaded images on the server.

Step 8

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




Before file uploading, your "~/Content/upload_files/" server folder will be empty.


After the files are uploaded, it will contain the image files.


Now, type "http://{your_site_url}/Content/upload_files/no-img.png" URL in your browser and you will be able to see the following.


This means you can access the files as long as you know the link. It doesn't matter whether the user is logged into the system or not.

Conclusion

In this article, we learned about uploading of images as files on ASP.NET MVC5 platform. You also learned to store image/file on your server in a fixed folder. Not only this, we saw the advantages & disadvantages of storing image/files as files.