To Retrieve/Show Image from SQL database - "ASP.NET CODE"


  • Just Right click on the Project Name below the Solution in 'solution explorer'(Top-Right hand side of DOTNET app).
  • Select "add new item"
  • Select "Generic Handler" and Press OK.
  • And Write the following code. Save it as "ShowImage.ashx"


<%@ WebHandler Language="C#" Class="ShowImage" %>


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

public class ShowImage : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
Int32 empno;
if (context.Request.QueryString["id"] != null)
empno = Convert.ToInt32(context.Request.QueryString["id"]);
else
throw new ArgumentException("No parameter specified");

context.Response.ContentType = "image/jpeg";
Stream strm = ShowEmpImage(empno);
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);
}
//context.Response.BinaryWrite(buffer);
}

public Stream ShowEmpImage(int empno)
{
SqlConnection connection = new SqlConnection("database=master;server=.;uid=sa");
string sql = "SELECT Image FROM new_account WHERE mno= @ID";
SqlCommand cmd = new SqlCommand(sql,connection);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@ID", empno);
connection.Open();
object img = cmd.ExecuteScalar();
try
{
return new MemoryStream((byte[])img);
}
catch
{
return null;
}
finally
{
connection.Close();
}
}

public bool IsReusable
{
get
{
return false;
}
}


}



To Retrive/Show image from SQL database, the above file must be called in an another 'aspx' form.To do so, Write the following code in an another form, where you want to retrieve/show image using a id:


protected void Button1_Click(object sender, EventArgs e)
{

Image1.ImageUrl = "ShowImage.ashx?id=" + TextBox1.Text;
SqlConnection db = new SqlConnection("database=master;server=.;uid=sa");
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
db.Open();
cmd.Connection = db;
cmd.CommandText="select *from new_account where mno=' " + TextBox1.Text + " ' ";
dr = cmd.ExecuteReader()
dr.Dispose();

}

0 comments:

Post a Comment

Popular Posts