ASP.NET MVC5 - Upload Images/Files As Document

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

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](maxNOT NULL,  
  23.  [file_ext] [nvarchar](maxNOT NULL,  
  24.  [file_path] [nvarchar](maxNOT 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 = ONON [PRIMARY]  
  29. ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]  
  30.   
  31. GO  
  32. /****** Object:  StoredProcedure [dbo].[sp_get_all_files]    Script Date: 11/19/2018 8:11:10 AM ******/  
  33. SET ANSI_NULLS ON  
  34. GO  
  35. SET QUOTED_IDENTIFIER ON  
  36. GO  
  37. -- =============================================  
  38. -- Author:  <Author,,Name>  
  39. -- Create date: <Create Date,,>  
  40. -- Description: <Description,,>  
  41. -- =============================================  
  42. CREATE PROCEDURE [dbo].[sp_get_all_files]  
  43.    
  44. AS  
  45. BEGIN  
  46. /****** Script for SelectTopNRows command from SSMS  ******/  
  47.  SELECT [file_id]  
  48.     ,[file_name]  
  49.     ,[file_ext]  
  50.  FROM [db_img].[dbo].[tbl_file]  
  51. END  
  52.   
  53. GO  
  54. /****** Object:  StoredProcedure [dbo].[sp_get_file_details]    Script Date: 11/19/2018 8:11:10 AM ******/  
  55. SET ANSI_NULLS ON  
  56. GO  
  57. SET QUOTED_IDENTIFIER ON  
  58. GO  
  59. -- =============================================  
  60. -- Author:  <Author,,Name>  
  61. -- Create date: <Create Date,,>  
  62. -- Description: <Description,,>  
  63. -- =============================================  
  64. CREATE PROCEDURE [dbo].[sp_get_file_details]   
  65.  @file_id INT  
  66. AS  
  67. BEGIN  
  68. /****** Script for SelectTopNRows command from SSMS  ******/  
  69.  SELECT [file_id]  
  70.     ,[file_name]  
  71.     ,[file_ext]  
  72.     ,[file_path]  
  73.  FROM [db_img].[dbo].[tbl_file]  
  74.  WHERE [tbl_file].[file_id] = @file_id  
  75. END  
  76.   
  77. GO  
  78. /****** Object:  StoredProcedure [dbo].[sp_insert_file]    Script Date: 11/19/2018 8:11:10 AM ******/  
  79. SET ANSI_NULLS ON  
  80. GO  
  81. SET QUOTED_IDENTIFIER ON  
  82. GO  
  83. -- =============================================  
  84. -- Author:  <Author,,Name>  
  85. -- Create date: <Create Date,,>  
  86. -- Description: <Description,,>  
  87. -- =============================================  
  88. CREATE PROCEDURE [dbo].[sp_insert_file]  
  89.  @file_name NVARCHAR(MAX),  
  90.  @file_ext NVARCHAR(MAX),  
  91.  @file_path NVARCHAR(MAX)  
  92. AS  
  93. BEGIN  
  94. /****** Script for SelectTopNRows command from SSMS  ******/  
  95.  INSERT INTO [dbo].[tbl_file]  
  96.            ([file_name]  
  97.            ,[file_ext]  
  98.            ,[file_path])  
  99.      VALUES  
  100.            (@file_name  
  101.            ,@file_ext  
  102.            ,@file_path)  
  103. END  
  104.   
  105. 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.   
  10.     <!-- Font Awesome -->  
  11.     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" />  
  12.   
  13. </head>  
  14. <body>  
  15.     <div class="navbar navbar-inverse navbar-fixed-top">  
  16.         <div class="container">  
  17.             <div class="navbar-header">  
  18.                 <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">  
  19.                     <span class="icon-bar"></span>  
  20.                     <span class="icon-bar"></span>  
  21.                     <span class="icon-bar"></span>  
  22.                 </button>  
  23.             </div>  
  24.         </div>  
  25.     </div>  
  26.     <div class="container body-content">  
  27.         @RenderBody()  
  28.         <hr />  
  29.         <footer>  
  30.             <center>  
  31.                 <p><strong>Copyright © @DateTime.Now.Year - <a href="http://wwww.asmak9.com/">Asma's Blog</a>.</strong> All rights reserved.</p>  
  32.             </center>  
  33.         </footer>  
  34.     </div>  
  35.   
  36.     @*Scripts*@  
  37.     @Scripts.Render("~/bundles/jquery")  
  38.   
  39.     @Scripts.Render("~/bundles/jqueryval")  
  40.     @Scripts.Render("~/bundles/bootstrap")  
  41.   
  42.     @RenderSection("scripts", required: false)  
  43. </body>  
  44. </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.   
  8. namespace MVCImageSaveFile.Helper_Code.Objects  
  9. {  
  10.     using System;  
  11.     using System.Collections.Generic;  
  12.     using System.Linq;  
  13.     using System.Web;  
  14.   
  15.     /// <summary>  
  16.     /// Image object class.  
  17.     /// </summary>  
  18.     public class ImgObj  
  19.     {  
  20.         #region Properties  
  21.   
  22.         /// <summary>  
  23.         /// Gets or sets Image ID.  
  24.         /// </summary>  
  25.         public int FileId { getset; }  
  26.   
  27.         /// <summary>  
  28.         /// Gets or sets Image name.  
  29.         /// </summary>  
  30.         public string FileName { getset; }  
  31.   
  32.         /// <summary>  
  33.         /// Gets or sets Image extension.  
  34.         /// </summary>  
  35.         public string FileContentType { getset; }  
  36.  
  37.         #endregion  
  38.     }  

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.   
  8. namespace MVCImageSaveFile.Models  
  9. {  
  10.     using System.Collections.Generic;  
  11.     using System.ComponentModel.DataAnnotations;  
  12.     using System.Web;  
  13.     using Helper_Code.Objects;  
  14.   
  15.     /// <summary>  
  16.     /// Image view model class.  
  17.     /// </summary>  
  18.     public class ImgViewModel  
  19.     {  
  20.         #region Properties  
  21.   
  22.         /// <summary>  
  23.         /// Gets or sets Image file.  
  24.         /// </summary>  
  25.         [Required]  
  26.         [Display(Name = "Upload File")]  
  27.         public HttpPostedFileBase FileAttach { getset; }  
  28.   
  29.         /// <summary>  
  30.         /// Gets or sets Image file list.  
  31.         /// </summary>  
  32.         public List<ImgObj> ImgLst { getset; }  
  33.  
  34.         #endregion  
  35.     }  

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

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

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.