Monday, December 21, 2009

Storing and Retrieving image in SQL server 2005 & asp.net using large value data type & HTTP handler


APSX page :

Handler code: image-handler.ashx

using System;
using System.Web;
using System.IO;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Configuration;
public class image_handler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string xStrCon = System.Configuration.ConfigurationManager.ConnectionStrings["conStrImage"].ConnectionString;
SqlConnection xCon = new SqlConnection(xStrCon);
xCon.Open();
SqlCommand xCom = new SqlCommand(“select * from images where”, xCon);
SqlDataAdapter xAda = new SqlDataAdapter(xCom);
DataSet ds = new DataSet();
xAda.Fill(ds);
// Image processing starts
byte[] bytImage = ReadFile(context.Server.MapPath(“banner.JPG”));
xCom.CommandText = “insert into images values(2,’kensington’,@imagedata)”;
xCom.Parameters.Add(new SqlParameter(“@imagedata”, (object)bytImage));
xCon.Close();
//Display image from SQL server
byte[] imageData = (byte[])ds.Tables[0].Rows[0][2];
context.Response.Clear();
context.Response.ContentType = “image/JPEG”;
context.Response.OutputStream.Write(imageData, 0, imageData.Length);
}
byte[] ReadFile(string sPath)
{
//Initialize byte array with a null value initially.
byte[] data = null;
//Use FileInfo object to get file size.
FileInfo fInfo = new FileInfo(sPath);
long numBytes = fInfo.Length;
//Open FileStream to read file
FileStream fStream = new FileStream(sPath, FileMode.Open, FileAccess.Read);
//Use BinaryReader to read file stream into byte array.
BinaryReader br = new BinaryReader(fStream);
//When you use BinaryReader, you need to supply number of bytes to read from file.
//In this case we want to read entire file. So supplying total number of bytes.
data = br.ReadBytes((int)numBytes);
return data;
}
public bool IsReusable
{
get
{
return false;
}
}
}

No comments:

Post a Comment