Friday 9 March 2012

How to store and retrieve images into databse in binary format.

In design page

<div id="new" align="left">
<p><label>Name:</label>
    <asp:Image ID="Image1" runat="server"  ImageAlign="Right" ImageUrl="~/images/commentbox.gif"/></p>
<div style=" padding-left:15px;">
    <asp:TextBox ID="TextBox1" runat="server" Width="191px"></asp:TextBox></div>
<p align="left"><label>E-mail</label></p>
<div align="left" style=" padding-left:15px;">
    <asp:TextBox ID="TextBox2" runat="server" Width="191px"></asp:TextBox></div>
   
<p align="left"><label>Upload Profile Picture</label></p>
<div align="left" style=" padding-left:15px;">
    <asp:FileUpload ID="FileUpload1" runat="server" /></div>  
  <div>
<label align="left">Comments/queries</label></div>
<div id="selector" align="left">

    <asp:TextBox ID="TextBox3" runat="server" TextMode="MultiLine" Height="80px"
        Width="585px"></asp:TextBox>
 
        </div>
             <div align="right" style="width: 71%">
    <asp:ImageButton ID="ImageButton1" runat="server" width="120px" Height="30"
        ImageUrl="~/images/comment.png" onclick="ImageButton1_Click"/>

       
       
        </div>
</div>
<br />
    <div>
        <asp:Label ID="Label1" runat="server" Text=""></asp:Label></div>
        ///// Inserting Into database
<div  id="selector2">
<br />
<asp:DataList ID="ddl1" runat="server" Width="620px"
        onitemcommand="ddl1_ItemCommand"
        onselectedindexchanged="ddl1_SelectedIndexChanged">
<ItemTemplate>
<div class="outr">
<table width="100%">
<tr><div style=" background-color:Maroon; padding-left:10px;"><asp:Label ID="name" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "SE_name") %>' Font-Bold="true" ForeColor="White" Font-Size="Small" ></asp:Label></div></tr>
<tr>
<td valign="top" width="20%"><asp:Image ID="Image1" runat="server" 
         ImageUrl='<%# "GetImage.aspx?id=" + Eval("SE_commentid") %>' width="100px" Height="100px" align="left" BorderStyle="Solid" BorderColor="Black" BorderWidth="1px"/> 
         //// Please observe here 'm using image handler
         </td>
<td valign="top" width="80%"><div><asp:TextBox ID="txt1" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "SE_comment")%>' CssClass="expanding" AutoPostBack="false" TextMode="MultiLine" Width="100%" BorderStyle="None" style="resize:none;"></asp:TextBox></div></td>

</tr>
<tr> </tr>
</table>
    <asp:Button ID="hiddenbutton" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "SE_commentid") %>' visible="false" />
<%--<div><textarea runat="server" text='<%# DataBinder.Eval(Container.DataItem, "SE_comment")%>'></textarea></div>--%>
<div style="padding-left:10px;" align="right">
 <font style=" font-size:small; font-weight:bold;">Posted date:</font><asp:Label ID="Label2" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "SE_posteddate") %>' Font-Bold="true" ForeColor="DarkOliveGreen" Font-Size="Small" ></asp:Label><asp:Label
    ID="Label3" runat="server" ></asp:Label></div>
 
</div>
<%-- <hr  width="100%" color="#EEE6E6"/>--%>
<br />

</ItemTemplate>
</asp:DataList>
    <asp:Label ID="Label5" runat="server" Visible="false"></asp:Label>
</div>      
////// Retreiving from database




In code behind


 protected void Page_Load(object sender, EventArgs e)
    {
        string connstr = ConfigurationManager.ConnectionStrings["smartedu"].ConnectionString;
        SqlConnection con = new SqlConnection(connstr);
        try
        {
           // SqlCommand cmd = new SqlCommand("select top 10 * from Commentbox order by SE_commentid Desc", con);

           // cmd.Connection.Open();

           //ddl1.DataSource = cmd.ExecuteReader();

           //ddl1.DataBind();

   
            string query = "select top 10 * from Commentbox order by SE_commentid Desc";
            SqlDataAdapter da = new SqlDataAdapter(query, con);
            DataTable table = new DataTable();

            da.Fill(table);
            ddl1.DataSource = table;
            ddl1.DataBind();

            //cmd.Connection.Close();
            //cmd.Connection.Dispose();
        }
        catch (Exception ex)
        {
            Label1.Text = ex.Message;
        }
       
    }
    protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
    {
        string connstr = ConfigurationManager.ConnectionStrings["smartedu"].ConnectionString;
        SqlConnection conn = new SqlConnection(connstr);
        SqlCommand cmd = new SqlCommand();
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandText = "dbo.comment";
   
        cmd.Parameters.AddWithValue("@name",TextBox1.Text);
        cmd.Parameters.AddWithValue("@email", TextBox2.Text);
        cmd.Parameters.AddWithValue("@comment", TextBox3.Text);
   

        if (FileUpload1.HasFile)
        {
            //getting length of uploaded file
            int length = FileUpload1.PostedFile.ContentLength;
            //create a byte array to store the binary image data
            byte[] imgbyte = new byte[length];
            //store the currently selected file in memeory
            HttpPostedFile img = FileUpload1.PostedFile;
            //set the binary data
            img.InputStream.Read(imgbyte, 0, length);
           // string imagename = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
            //use the web.config to store the connection string

            //string newimagename = TextBox1.Text + imagename;

            // Session["imagepreserve"] = imgbyte;
            //con.Open();
            //SqlCommand cmd1 = new SqlCommand("SELECT  max(SE_Regcollid) FROM institutereg", con);

            //int res = (int)cmd1.ExecuteScalar();
            //int newres = (res + 1);
            //string newid = TextBox1.Text + newres;
            //con.Close();


            //  con.Open();

           /// cmd.Parameters.AddWithValue("@imagename", newimagename);
           ///
            cmd.Parameters.AddWithValue("@image", imgbyte);

            //  con.Close();

        }
        else
        {


            string filePath = Server.MapPath("~/images/nocommentimage.png");
            Byte[] imgByte = System.IO.File.ReadAllBytes(filePath);

          //  string newimagename = TextBox1.Text + "imagenotfound";
            //con.Open();
            //SqlCommand cmd1 = new SqlCommand("SELECT  max(SE_Regcollid) FROM institutereg", con);

            //int res = (int)cmd1.ExecuteScalar();
            //int newres = (res + 1);
            //string newid = TextBox1.Text + newres;
            //con.Close();


            cmd.Parameters.AddWithValue("@image", imgByte);


        }


        cmd.Connection = conn;

        try
        {
            conn.Open();
            cmd.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            Label1.Text = ex.Message;
        }

     
    }

    protected void ImageButton2_click(object sender, ImageClickEventArgs e)
    {
     
        string connstr = ConfigurationManager.ConnectionStrings["smartedu"].ConnectionString;
        SqlConnection con = new SqlConnection(connstr);
        string id = Request.QueryString["id"];

        SqlCommand cmd = new SqlCommand("SELECT SE_vote from Commentbox where SE_commentid = '" + id + " '", con);

       con.Open();

       Label5.Text = cmd.ExecuteScalar().ToString();

       con.Close();
       

     

    }

    protected void ddl1_ItemCommand(object source, DataListCommandEventArgs e)
    {

        if (e.CommandName == "view")
        {
            Button hb = (Button)(e.Item.FindControl("hiddenbutton"));
            Response.Redirect("comments.aspx?id=" + hb.Text);
        }

    }


In image handler

Just create the new page and save it as GetImage.aspx .




  protected void Page_Load(object sender, EventArgs e)
    {
        string id = Request.QueryString["id"];

        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["smartedu"].ConnectionString);
        string imageid = Request.QueryString["id"];

        con.Open();
        SqlCommand command = new SqlCommand("select SE_image from Commentbox where SE_commentid=" + imageid, con);
        SqlDataReader dr = command.ExecuteReader();
        dr.Read();
        Response.BinaryWrite((Byte[])dr[0]);
        con.Close();
        Response.End();
    }



thats it...................

No comments:

Post a Comment