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.

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.
- 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.
- Storing of the uploaded file is guaranteed.
- Images/Files store on database do not require extra backups.
- 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.
- Image replication is easy (if needed).
- 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)
- Database storage becomes expensive for many and large file storage.
- There will be a performance penalty as latency to retrieve image/file is slower and database lookup is slower than filesystem lookup.
- Additional code is needed to extract and stream files.
- 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.
- There will be more load on the database.
- Web server bandwidth will increase which adds additional costs.
Prerequisites
Following are some prerequisites before you proceed any further in this tutorial:
- Knowledge of ASP.NET MVC5.
- Knowledge of HTML.
- Knowledge of Bootstrap.
- 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
- USE [db_img]
- GO
- /****** Object: StoredProcedure [dbo].[sp_insert_file] Script Date: 11/18/2018 12:27:55 AM ******/
- DROP PROCEDURE [dbo].[sp_insert_file]
- GO
- /****** Object: StoredProcedure [dbo].[sp_get_file_details] Script Date: 11/18/2018 12:27:55 AM ******/
- DROP PROCEDURE [dbo].[sp_get_file_details]
- GO
- /****** Object: StoredProcedure [dbo].[sp_get_all_files] Script Date: 11/18/2018 12:27:55 AM ******/
- DROP PROCEDURE [dbo].[sp_get_all_files]
- GO
- /****** Object: Table [dbo].[tbl_file] Script Date: 11/18/2018 12:27:55 AM ******/
- DROP TABLE [dbo].[tbl_file]
- GO
- /****** Object: Table [dbo].[tbl_file] Script Date: 11/18/2018 12:27:55 AM ******/
- SET ANSI_NULLS ON
- GO
- SET QUOTED_IDENTIFIER ON
- GO
- CREATE TABLE [dbo].[tbl_file](
- [file_id] [int] IDENTITY(1,1) NOT NULL,
- [file_name] [nvarchar](max) NOT NULL,
- [file_ext] [nvarchar](max) NOT NULL,
- [file_base6] [nvarchar](max) NOT NULL,
- CONSTRAINT [PK_tbl_file] PRIMARY KEY CLUSTERED
- (
- [file_id] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
- GO
- /****** Object: StoredProcedure [dbo].[sp_get_all_files] Script Date: 11/18/2018 12:27:55 AM ******/
- SET ANSI_NULLS ON
- GO
- SET QUOTED_IDENTIFIER ON
- GO
- -- =============================================
- -- Author: <Author,,Name>
- -- Create date: <Create Date,,>
- -- Description: <Description,,>
- -- =============================================
- CREATE PROCEDURE [dbo].[sp_get_all_files]
- AS
- BEGIN
- /****** Script for SelectTopNRows command from SSMS ******/
- SELECT [file_id]
- ,[file_name]
- ,[file_ext]
- FROM [db_img].[dbo].[tbl_file]
- END
- GO
- /****** Object: StoredProcedure [dbo].[sp_get_file_details] Script Date: 11/18/2018 12:27:55 AM ******/
- SET ANSI_NULLS ON
- GO
- SET QUOTED_IDENTIFIER ON
- GO
- -- =============================================
- -- Author: <Author,,Name>
- -- Create date: <Create Date,,>
- -- Description: <Description,,>
- -- =============================================
- CREATE PROCEDURE [dbo].[sp_get_file_details]
- @file_id INT
- AS
- BEGIN
- /****** Script for SelectTopNRows command from SSMS ******/
- SELECT [file_id]
- ,[file_name]
- ,[file_ext]
- ,[file_base6]
- FROM [db_img].[dbo].[tbl_file]
- WHERE [tbl_file].[file_id] = @file_id
- END
- GO
- /****** Object: StoredProcedure [dbo].[sp_insert_file] Script Date: 11/18/2018 12:27:55 AM ******/
- SET ANSI_NULLS ON
- GO
- SET QUOTED_IDENTIFIER ON
- GO
- -- =============================================
- -- Author: <Author,,Name>
- -- Create date: <Create Date,,>
- -- Description: <Description,,>
- -- =============================================
- CREATE PROCEDURE [dbo].[sp_insert_file]
- @file_name NVARCHAR(MAX),
- @file_ext NVARCHAR(MAX),
- @file_base64 NVARCHAR(MAX)
- AS
- BEGIN
- /****** Script for SelectTopNRows command from SSMS ******/
- INSERT INTO [dbo].[tbl_file]
- ([file_name]
- ,[file_ext]
- ,[file_base6])
- VALUES
- (@file_name
- ,@file_ext
- ,@file_base64)
- END
- GO
Step 2
Step 3
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>@ViewBag.Title</title>
- @Styles.Render("~/Content/css")
- @Scripts.Render("~/bundles/modernizr")
- <!-- Font Awesome -->
- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" />
- </head>
- <body>
- <div class="navbar navbar-inverse navbar-fixed-top">
- <div class="container">
- <div class="navbar-header">
- <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
- <span class="icon-bar"></span>
- <span class="icon-bar"></span>
- <span class="icon-bar"></span>
- </button>
- </div>
- </div>
- </div>
- <div class="container body-content">
- @RenderBody()
- <hr />
- <footer>
- <center>
- <p><strong>Copyright © @DateTime.Now.Year - <a href="http://wwww.asmak9.com/">Asma's Blog</a>.</strong> All rights reserved.</p>
- </center>
- </footer>
- </div>
- @*Scripts*@
- @Scripts.Render("~/bundles/jquery")
- @Scripts.Render("~/bundles/jqueryval")
- @Scripts.Render("~/bundles/bootstrap")
- @RenderSection("scripts", required: false)
- </body>
- </html>
In the above code, I have simply created a basic default layout page and linked the required libraries into it.
Step 4
- //-----------------------------------------------------------------------
- // <copyright file="ImgObj.cs" company="None">
- // Copyright (c) Allow to distribute this code and utilize this code for personal or commercial purpose.
- // </copyright>
- // <author>Asma Khalid</author>
- //-----------------------------------------------------------------------
- namespace ImgSaveDb.Helper_Code.Objects
- {
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- /// <summary>
- /// Image object class.
- /// </summary>
- public class ImgObj
- {
- #region Properties
- /// <summary>
- /// Gets or sets Image ID.
- /// </summary>
- public int FileId { get; set; }
- /// <summary>
- /// Gets or sets Image name.
- /// </summary>
- public string FileName { get; set; }
- /// <summary>
- /// Gets or sets Image extension.
- /// </summary>
- public string FileContentType { get; set; }
- #endregion
- }
- }
In the above code, I have simply created an object class which will map my image file metadata from SQL database.
Step 5
- //-----------------------------------------------------------------------
- // <copyright file="ImgViewModel.cs" company="None">
- // Copyright (c) Allow to distribute this code and utilize this code for personal or commercial purpose.
- // </copyright>
- // <author>Asma Khalid</author>
- //-----------------------------------------------------------------------
- namespace ImgSaveDb.Models
- {
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations;
- using System.Web;
- using Helper_Code.Objects;
- /// <summary>
- /// Image view model class.
- /// </summary>
- public class ImgViewModel
- {
- #region Properties
- /// <summary>
- /// Gets or sets Image file.
- /// </summary>
- [Required]
- [Display(Name = "Upload File")]
- public HttpPostedFileBase FileAttach { get; set; }
- /// <summary>
- /// Gets or sets Image file list.
- /// </summary>
- public List<ImgObj> ImgLst { get; set; }
- #endregion
- }
- }
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



Sơn LêPosted Sep 11, 2020, 9:45 AM
Thank you very much! But this way can be writting in EF Code First?
Malik HassanPosted May 19, 2020, 1:40 PM
Browse button not shown properly .. pl help ..thank you
Roberto RazzettiPosted Feb 25, 2020, 4:47 AM
Very well done! It works fine for me. Thank you so much!
John SmithPosted Jan 11, 2020, 5:49 AM
Good article but I struggled when adding the databaseManager private property in the imgcontroller code. As this is aimed at beginners it would be helpful if you mention that we need to add the DB first data item before adding the controller code. Once I added EF 6 all was well.
Reshma FrancisPosted Dec 6, 2019, 12:08 AM
When we try to insert into database it insert not like base 64..please help us
Alice NguyenPosted Nov 28, 2018, 9:27 PM
I really enjoyed this. Thank you for sharing. Be well.
First LastPosted Nov 28, 2018, 10:20 AM
This is uses the Database First approach in Entity Frameworks correct?