Tuesday, September 11, 2012

Image Upload and Display using Handler


//code behind Button click for Uploading


f (FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != null)
                 {
                     byte[] myimage = new byte[FileUpload1.PostedFile.ContentLength];
                     HttpPostedFile image = FileUpload1.PostedFile;
                     image.InputStream.Read(myimage, 0, (int)FileUpload1.PostedFile.ContentLength);

                   
                     SqlCommand cmd1 = new SqlCommand("insert into user_temp_sell values('" + user + "','" + Label8.Text + "','" + DropDownList1.SelectedItem.Text + "','" + TextBox7.Text + "','" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "','" + TextBox5.Text + "',@image1,'" + TextBox6.Text + "')", con);
                     cmd1.Parameters.Add("@image1", SqlDbType.Image, myimage.Length).Value = myimage;
                     cmd1.ExecuteNonQuery();
}


//// to call handler


 Image1.ImageUrl = "Handler.ashx?image_id=" + Convert.ToInt16(Label9.Text);




//code to be on handler 

<%@ WebHandler Language="C#" Class="Handler" %> 
using System;
using System.Web;
using System.Configuration;
using System.Data.SqlClient;

public class Handler : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        try
        {
            SqlConnection con = new SqlConnection();
            con.ConnectionString = ConfigurationManager.ConnectionStrings
                                  ["eshoppeeConnectionString"].ConnectionString;

            con.Open();
          
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "Select image from imgtab" +
                              " where image_id =@image_id";
            cmd.CommandType = System.Data.CommandType.Text;
            cmd.Connection = con;

            SqlParameter ImageID = new SqlParameter
                                ("@image_id", System.Data.SqlDbType.Int);
            ImageID.Value = context.Request.QueryString["image_id"];
            cmd.Parameters.Add(ImageID);

            SqlDataReader dReader = cmd.ExecuteReader();
            dReader.Read();
            context.Response.BinaryWrite((byte[])dReader["image"]);
            dReader.Close();
            con.Close();
        }
        catch
        {
        }
   
    }

    #region IHttpHandler Members

    public bool IsReusable
    {
        get { throw new Exception("The method or operation is not implemented."); }
    }

    #endregion
}

No comments:

Post a Comment