To Display Image thats stored as Type Image in DB

To Display Image thats stored as Type Image in DB

ASPX Page

<html xmlns=”http://www.w3.org/1999/xhtml” >
<head runat=”server”>
<title>Untitled Page</title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<asp:GridView ID=”gvwImages” runat=”server”
AutoGenerateColumns=”false”
DataSourceID=”dsImages”>
<%–DataSourceID=”dsImages”–%>
<Columns>

<asp:TemplateField HeaderText=”Name”>
<ItemTemplate>
<%–//field img_name is the name given to image–%>
<asp:Label ID=”lblName” runat=”server” Text=’<%#Eval(“img_name”) %>’>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText=”Image”>
<ItemTemplate>
<%–//here field img_id is the id of the image–%>
<asp:Image ID=”Image1″ runat=”server”
ImageUrl=’<%# “Handler.ashx?id=” + Eval(“img_id”) %>’ />
</ItemTemplate>
</asp:TemplateField>

</Columns>

</asp:GridView>
<asp:SqlDataSource ID=”dsImages” runat=”server”
ConnectionString=’<%$ConnectionStrings: LoginCon %>’
SelectCommand=”Select img_id,img_name from Images”>
</asp:SqlDataSource>
</div>
</form>
</body>
</html>

In Handler.ashx

<%@ WebHandler Language=”C#” Class=”Handler” %>

using System;
using System.Web;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

public class Handler : IHttpHandler
{

public bool IsReusable
{
get {return false;}
}
public void ProcessRequest(HttpContext context)
{
SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["LoginCon"].ConnectionString);
myConnection.Open();
//here field img_data is the content of the image (type image in DB)
//field img_contenttype is the type of the image (optional)
string sql = “Select img_data,img_contenttype from Images where img_id=@ImageId”;
SqlCommand cmd = new SqlCommand(sql, myConnection);
cmd.Parameters.Add(“@ImageId”, SqlDbType.Int).Value = context.Request.QueryString["id"];
cmd.Prepare();
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
context.Response.ContentType = dr["img_contenttype"].ToString();
context.Response.BinaryWrite((byte[])dr["img_data"]);
}

}

Leave a Reply

You must be logged in to post a comment.