Create a generic handler like
// DBImageHandler.ashx
Now you can use Image link as
DbImageHandler.ashx?id=1
Exmaple :
// DBImageHandler.ashx
<%@ WebHandler Language="C#" Class="DbImageHandler" %>
using System;
using System.Web;
using System.IO;
public class DbImageHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
Int32 id;
if (context.Request.Params["id"] != null)
id = Convert.ToInt32(context.Request.Params["id"]);
else
throw new ArgumentException("No parameter specified");
context.Response.ContentType = "image/jpeg";
Stream strm = getDBImage(id);
byte[] buffer = new byte[4096];
int byteSeq = strm.Read(buffer, 0, 4096);
while (byteSeq > 0)
{
context.Response.OutputStream.Write(buffer, 0, byteSeq);
byteSeq = strm.Read(buffer, 0, 4096);
}
}
public Stream getDBImage(int id)
{
System.Data.SqlClient.SqlDataAdapter da = new System.Data.SqlClient.SqlDataAdapter("SELECT photo FROM Employee WHERE EmployeeID=" + id, System.Configuration.ConfigurationManager.ConnectionStrings["DBConStr"].ConnectionString);
System.Data.DataTable dt = new System.Data.DataTable();
da.Fill(dt);
if (dt.Rows.Count == 0)
return null;
return new MemoryStream((byte[])dt.Rows[0]["photo"]);
}
public bool IsReusable
{
get
{
return false;
}
}
}
Now you can use Image link as
DbImageHandler.ashx?id=1
Exmaple :
<img src="DbImageHandler.ashx?id=1" alt="Employee 1 Photo" width="400px" height="400px" />
No comments:
Post a Comment