In this article I am going to show how we can upload
and show images from Data Base in ASP.NET MVC 4.
I am showing this functionality by creating an asp.net
MVC 4 application (R- An Image Gallery
Application In MVC 4).
Below is my SQL Server Data Table structure: (Album_Details)

Image 1.
Now Open Visual Studio -> File -> New Project:

Image 2.

Image 3.
Now Right Click on Model Folder Add New
Item-> Add New Class (ImageInfo):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace AnImageGalleryApplicationInMVC4.Models
{
public class ImageInfo
{
public int Image_Id { get; set; }
public string Image_Name { get; set; }
public byte[] Image { get; set; }
public string Image_UploadedDate { get; set; }
}
}
Now Again Right Click on Model Folder-> Add New Item
-> Add New Class(RAlbumService) :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
namespace AnImageGalleryApplicationInMVC4.Models
{
public class RAlbumService
{
public IList<ImageInfo> GetAllImages()
{
List<ImageInfo> objImgInfo = new List<ImageInfo>();
SqlDataAdapter da;
DataSet ds = new DataSet();
SqlConnection con = new SqlConnection();
con.ConnectionString = @"Data Source=MYPC\SqlServer2k8;Integrated Security=true;Initial Catalog=R-ImageGallery";
SqlCommand cmd = new SqlCommand("SELECT * FROM Album_Details", con);
da = new SqlDataAdapter(cmd);
da.Fill(ds);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
if (!object.Equals(ds.Tables[0], null))
{
if (ds.Tables[0].Rows.Count > 0)
{
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
ImageInfo objThisIMGInfo = new ImageInfo();
objThisIMGInfo.Image_Id
= Convert.ToInt32(ds.Tables[0].Rows[i]["IMG_ID"]);
objThisIMGInfo.Image_Name = ds.Tables[0].Rows[i]["ImageName"].ToString();
objThisIMGInfo.Image = (byte[])ds.Tables[0].Rows[i]["Photo"];
objThisIMGInfo.Image_UploadedDate = ds.Tables[0].Rows[i]["UploadedDate"].ToString().Split(' ')[0];
objImgInfo.Add(objThisIMGInfo);
}
}
}
return objImgInfo.ToList();
}
public byte[] GetImageDetails(int id)
{
SqlConnection con = new SqlConnection(@"Data Source=MYPC\SqlServer2k8;Integrated Security=true;Initial
Catalog=R-ImageGallery");
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT Photo FROM Album_Details where IMG_ID=@ImageId";
cmd.Parameters.AddWithValue("@ImageId", id);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
ImageInfo objImageInfo = new ImageInfo();
while (dr.Read())
{
objImageInfo.Image = (byte[])dr["Photo"];
}
return objImageInfo.Image;
}
}
public int UploadImage(ImageInfo objImageInfo)
{
SqlConnection con = new SqlConnection(@"Data Source=MYPC\SqlServer2k8;Integrated Security=true;Initial
Catalog=R-ImageGallery");
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO Album_Details(ImageName,Photo)
VALUES(@ImageName,@Photo)";
cmd.Parameters.AddWithValue("@ImageName", objImageInfo.Image_Name);
cmd.Parameters.AddWithValue("@Photo", objImageInfo.Image);
con.Open();
int result = cmd.ExecuteNonQuery();
con.Close();
return result;
}
}
}
}
Now Right Click on Controller -> Add New
Controller(Albums):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AnImageGalleryApplicationInMVC4.Models;
using System.IO;
namespace AnImageGalleryApplicationInMVC4.Controllers
{
public class AlbumsController : Controller
{
RAlbumService objAlbumModelService = new RAlbumService();
[HttpGet]
public ActionResult Index()
{
return View(objAlbumModelService.GetAllImages().ToList());
}
public ActionResult GetImgInformation(int id)
{
byte[] cover = objAlbumModelService.GetImageDetails(id);
if (cover != null)
{
return File(cover, "image/jpg");
}
else
{
return null;
}
}
[HttpPost]
public ActionResult Index(FormCollection collection)
{
HttpPostedFileBase file = Request.Files["ImageData"];
ImageInfo objAlbumMaster = new ImageInfo();
objAlbumMaster.Image_Name =
collection["ImageName"].ToString();
objAlbumMaster.Image =
ConvertToBytes(file);
objAlbumModelService.UploadImage(objAlbumMaster);
return View(objAlbumModelService.GetAllImages().ToList());
}
public byte[] ConvertToBytes(HttpPostedFileBase image)
{
byte[] imageBytes = null;
BinaryReader reader = new BinaryReader(image.InputStream);
imageBytes = reader.ReadBytes((int)image.ContentLength);
return imageBytes;
}
}
}
Now Right click on Index Method name add new view and
do the below code:
@model
IList<AnImageGalleryApplicationInMVC4.Models.ImageInfo>
@{
ViewBag.Title = "An Image Gallery Application In MVC 4";
}
<table>
<tr>
<td style="vertical-align: top; width: 15%;">
<table style="border: solid 2px Red; padding: 5px; width: 100%;">
<tr>
<td style="background-color: skyblue; color: red; text-align: center; font-weight: bold;">Upload Image
</td>
</tr>
<tr>
<td>
@using (Html.BeginForm("Index", "Albums", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<table style="width: 100%;">
<tr>
<td style="padding-left: 10px;">Name :
</td>
<td>@Html.TextBox("ImageName", "", new { style = "width:200px" })
</td>
</tr>
<tr>
<td style="padding-left: 10px;">Image :
</td>
<td>
<input type="file" name="ImageData" id="ImageData" />
</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" name="submit" value="Upload" />
</td>
</tr>
</table>
}
</td>
</tr>
</table>
</td>
<td style="vertical-align:top;">
<table style="border: solid 2px Green; padding: 5px; width: 100%;">
<tr>
<td colspan="4" style="background-color: skyblue; color: red; text-align: center; font-weight: bold;">All Uploaded Images
</td>
</tr>
<tr>
<td>
<table>
@{
const int ShowColumn = 3;
int OldRecords = 0;
var items = Model.Skip(OldRecords).Take(ShowColumn);
while (items.Count() > 0)
{
<tr>
@foreach (var item in items)
{
<td style="padding-left: 5px;">
<table>
<tr>
<td style="text-align: center;">
<img src="/Albums/GetImgInformation/@item.Image_Id" width="140" />
</td>
</tr>
<tr>
<td style="text-align: center; font-weight: bold; color: Teal">@item.Image_Name | @item.Image_UploadedDate
</td>
</tr>
</table>
</td>
}
</tr>
OldRecords
+= ShowColumn;
items =
Model.Skip(OldRecords).Take(ShowColumn);
}
}
</table>
</td>
</tr>
</table>
</td>
</tr>
</table>
Now Run your application:

Image 4.

Image 5.

Image 6.