Read image from database and write into response
<%@ WebHandler Language="C#" Class="Image" %>
using System;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;
public class Image : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
if (string.IsNullOrEmpty(context.Request.QueryString["id"]))
{
context.Response.StatusCode = "404";
context.Response.End();
}
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings[VarHelper.ConnStrLocal].ConnectionString))
{
SqlCommand cmd = new SqlCommand("SELECT [MimeType], [Image] FROM [ImageAlbum] WHERE [ImageID] = @ImageID", conn);
cmd.Parameters.Add("@ImageID", System.Data.SqlDbType.Int).Value = context.Request.QueryString["id"];
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
byte[] data = null;
string contentType = string.Empty;
while (reader.Read())
{
data = (byte[])reader["Image"];
contentType = (string)reader["MimeType"];
}
context.Response.ContentType = contentType;
context.Response.BinaryWrite(data);
context.Response.End();
}
else
{
context.Response.StatusCode = "404";
context.Response.End();
}
conn.Close();
}
}
public bool IsReusable
{
get
{
return false;
}
}
}