public class imageHandler : IHttpHandler
{
#region IHttpHandler Members
public bool IsReusable
{
get { return false; }
}
public void ProcessRequest(HttpContext context)
{
//Getting file name from incoming request.
string url = Path.GetFileName(context.Request.Path);
Guid FileId;
try
{
//Since we have all our primary keys stored in GUID
//Try parsing the file name to Guid
FileId = new Guid(Path.GetFileNameWithoutExtension(url));
}
catch (FormatException)
{
//If some other JPG file is requested
FileId = Guid.Empty;
}
if (FileId != Guid.Empty) // If the call is for valid Image File Stream
{
SqlConnection objSqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
objSqlCon.Open();
SqlTransaction objSqlTran = objSqlCon.BeginTransaction();
SqlCommand objSqlCmd = new SqlCommand("FileGet", objSqlCon, objSqlTran);
objSqlCmd.CommandType = CommandType.StoredProcedure;
SqlParameter objSqlParam1 = new SqlParameter("@ID", SqlDbType.VarChar);
objSqlParam1.Value = FileId.ToString();
objSqlCmd.Parameters.Add(objSqlParam1);
string path = string.Empty;
string fileType = string.Empty;
using (SqlDataReader sdr = objSqlCmd.ExecuteReader())
{
while (sdr.Read())
{
path = sdr[0].ToString();
fileType = sdr[1].ToString();
}
}
objSqlCmd = new SqlCommand("SELECT GET_FILESTREAM_TRANSACTION_CONTEXT()", objSqlCon, objSqlTran);
byte[] objContext = (byte[])objSqlCmd.ExecuteScalar();
SqlFileStream objSqlFileStream = new SqlFileStream(path, objContext, FileAccess.Read);
byte[] buffer = new byte[(int)objSqlFileStream.Length];
objSqlFileStream.Read(buffer, 0, buffer.Length);
objSqlFileStream.Close();
objSqlTran.Commit();
context.Response.AddHeader("Content-disposition", "attachment; filename=" + Path.GetFileName(path) + fileType);
// Here you need to manage the download file stuff according to your need
context.Response.ContentType = "application/octet-stream";
context.Response.BinaryWrite(buffer);
}
else
{ // If the call is for some other JPG file, nothing to do with file stream.
context.Response.WriteFile(context.Request.Path);
}
}