Create And Display Image By Binary Format Images from Database with Handler (ashx) file in Asp.net

This article explains how to show or display binary format images from database with handler ashx file in asp.net gridview control using c#, with example or upload images in binary format and displaying images from sql server database using handler ashx in asp.net gridview using c#.
Data Base Table:-

Column Name
Data Type
Allow Nulls
imageid
Int(IDENTITY=TRUE)
NO
imagename
varchar(50)
Yes
imagedata
varbinary(max)
Yes
 


aspx page:-

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
 <html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1">
<title>Display images from sql server database in asp.net gridview control</title>
<style type="text/css">
.GridviewDiv {font-size: 100%; font-family: 'Lucida Grande', 'Lucida Sans Unicode', Verdana, Arial, Helevetica, sans-serif; color: #303933;}
.headerstyle
{
color:#FFFFFF;border-right-color:#abb079;border-bottom-color:#abb079;background-color: #df5015;padding:0.5em 0.5em 0.5em 0.5em;text-align:center;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="fileUpload1" runat="server" /><br />
<asp:Button ID="btnUpload" runat="server" Text="Upload" onclick="btnUpload_Click" />
</div>
<div class="GridviewDiv">
<asp:GridView ID="gvImages" CssClass="Gridview" runat="server" AutoGenerateColumns="False">
<HeaderStyle CssClass="headerstyle" />
<Columns>
<asp:BoundField HeaderText = "Image Name" DataField="imagename" />
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl='<%# "ImageHandler.ashx?ImID="+ Eval("imageid") %>' Height="150px" Width="150px"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>  

C# Code:-
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
 string strCon = "Data Source=VEPSH;Integrated Security=true;Initial Catalog=MySampleDB";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridviewData();
}
}
// Bind Gridview Data
private void BindGridviewData()
{
using (SqlConnection con = new SqlConnection(strCon))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select imageid,imagename from imagedetails";
cmd.Connection = con;
con.Open();
gvImages.DataSource = cmd.ExecuteReader();
gvImages.DataBind();
con.Close();
}
}
}
// Save files to Folder and files path in database
protected void btnUpload_Click(object sender, EventArgs e)
{
//Condition to check if the file uploaded or not
if (fileUpload1.HasFile)
{
int length = fileUpload1.PostedFile.ContentLength;
byte[] imgbyte = new byte[length];
HttpPostedFile img = fileUpload1.PostedFile;
//set the binary data
img.InputStream.Read(imgbyte, 0, length); 
string filename = Path.GetFileName(fileUpload1.PostedFile.FileName);
using (SqlConnection con = new SqlConnection(strCon))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "insert into imagedetails(imagename,imagedata) values(@Name,@Data)";
cmd.Parameters.AddWithValue("@Name", filename);
cmd.Parameters.AddWithValue("@Data", imgbyte);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
BindGridviewData();
}
}
}
}

 Here HTTPHandler is a simple class that allows you to process a request and return a response to the browser. Simply we can say that a Handler is responsible for fulfilling requests from the browser. It can handle only one request at a time, which in turn gives high performance.
To add handler file Right Click on your project à select Add New Item à select Handler file à give name as ImageHandler.ashx like as shown in following image and click ok.

 Now open your ImageHandler.ashx file and write the following code
C# Code:-

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
 using System;
using System.Web;
using System.Data.SqlClient;
public class ImageHandler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
string imageid = context.Request.QueryString["ImID"];
SqlConnection con = new SqlConnection("Data Source=Suresh;Integrated Security=true;Initial Catalog=MySampleDB");
con.Open();
SqlCommand cmd = new SqlCommand("select imagedata from imagedetails where imageid=" + imageid, con);
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
context.Response.BinaryWrite((byte[])dr[0]);
con.Close();
context.Response.End();
}
public bool IsReusable {
get {
return false;
}
}
}

Ashwani
Ashwani

This is a short biography of the post author. Maecenas nec odio et ante tincidunt tempus donec vitae sapien ut libero venenatis faucibus nullam quis ante maecenas nec odio et ante tincidunt tempus donec.

No comments:

Post a Comment