Showing posts with label how to retrieve image saved in binary format from Sql Server database. Show all posts
Showing posts with label how to retrieve image saved in binary format from Sql Server database. Show all posts

Wednesday, August 22, 2018

how to save image in binary format in asp.net & Sql Server | sradha Webcreations

how to save image in binary format  in asp.net & Sql Server also retrieve same images 


ImageSave.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ImageSave.aspx.cs" Inherits="ImageSave" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <table>
<tr>
<td>
    SomeText</td>
<td>
    <asp:TextBox ID="TextBoxSomeText" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Image Name:
</td>
<td>
<asp:TextBox ID="txtImageName" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Upload Image:
</td>
<td>
<asp:FileUpload ID="fileuploadImage" runat="server" />
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Button ID="btnUpload" runat="server" Text="Upload" onclick="btnUpload_Click" />
</td>
</tr>
</table>
    </div>
    <div>
<!--<asp:gridview id="GridView1" runat="server" autogeneratecolumns="False">
       <columns>

           <asp:boundfield datafield="ImagePath" headertext="Header Text"></asp:boundfield>
           <asp:templatefield headertext="Image Form DataBase">

               <itemtemplate>
                   <img alt="Image" height="70px" src="<%# "ImageHandler.ashx?Id="+ Eval("id") %>" width="70px"/>
               </itemtemplate>
           </asp:templatefield>

       </columns>
   </asp:gridview>-->


   <asp:DataList ID="Datalist1" runat="server"  Width="100px" RepeatColumns="1">
   <ItemTemplate>
   <img alt="Image" height="70px" src="<%# "ImageHandler.ashx?Id="+ Eval("id") %>" width="70px"/>
   </ItemTemplate>
      </asp:DataList>
</div>
    </form>
</body>
</html>

ImageSave.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Security;

public partial class ImageSave : System.Web.UI.Page
{
    string strcon = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;
    protected void Page_Load(object sender, EventArgs e)
    {
        LoadData();
    }
    private void LoadData()
    {
        string returnValue = string.Empty;

        //Get the databse connection string from web.config file

        string conString = ConfigurationManager.ConnectionStrings["dbConnection"].ConnectionString;
        SqlConnection sqlConn = new SqlConnection(conString);
        SqlDataReader sqlDr = null;
        try
        {

            SqlCommand sqlCmd = new SqlCommand("GetImageInfoFromDB", sqlConn);
            sqlCmd.CommandType = CommandType.StoredProcedure;

            sqlConn.Open();
            sqlDr = sqlCmd.ExecuteReader();
            //Bind gridView

            //GridView1.DataSource = sqlDr;
            //GridView1.DataBind();

            Datalist1.DataSource = sqlDr;
            Datalist1.DataBind();
        }

        catch (Exception ex)
        {
            //Handle Error

        }
        finally
        {

            if (sqlDr != null && !sqlDr.IsClosed)
            {

                sqlDr.Close(); //close sqldatareader

            }

            sqlConn.Close();
        }
    }

    protected void btnUpload_Click(object sender, EventArgs e)
    {
        //Condition to check if the file uploaded or not
        if (fileuploadImage.HasFile)
        {
            //getting length of uploaded file
            int length = fileuploadImage.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 = fileuploadImage.PostedFile;
            //set the binary data
            img.InputStream.Read(imgbyte, 0, length);
            string imagename = txtImageName.Text;

            img.InputStream.Read(imgbyte, 0, length);
            string SomeText = TextBoxSomeText.Text;
            //use the web.config to store the connection string
            SqlConnection connection = new SqlConnection(strcon);
            connection.Open();
            SqlCommand cmd = new SqlCommand("INSERT INTO Image_Binary (SomeText,ImagePath,Image_Blob) VALUES (@SomeText,@ImagePath,@Image_Blob)", connection);
           
            cmd.Parameters.Add("@SomeText",SqlDbType.VarChar,50).Value=SomeText;
            cmd.Parameters.Add("@imagePath", SqlDbType.VarChar, 50).Value = imagename;
            cmd.Parameters.Add("@image_Blob", SqlDbType.Image).Value = imgbyte;
            int count = cmd.ExecuteNonQuery();
            connection.Close();
            if (count == 1)
            {
              //  BindGridData();
                txtImageName.Text = string.Empty;
                ScriptManager.RegisterStartupScript(this, this.GetType(), "alertmessage", "javascript:alert('" + imagename + " image inserted successfully')", true);
            }
        }
    }
   
}
ImageHandler.ashx
<%@ WebHandler Language="C#" Class="ImageHandler" %>

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


public class ImageHandler : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        // context.Response.ContentType = "text/plain";
        //context.Response.Write("Hello World");

        string strId = context.Request.QueryString["Id"];
        if (!string.IsNullOrEmpty(strId))
        {
            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["dbConnection"].ConnectionString);
            SqlDataReader sqlDr = null;
            try
            {
                conn.Open(); //open database connection

                SqlCommand sqlCmd = new SqlCommand("GetImageFromDB", conn);
                sqlCmd.CommandType = CommandType.StoredProcedure;

                //Add the parameter to SQLCommand object
                sqlCmd.Parameters.AddWithValue("@id", strId);
                sqlDr = sqlCmd.ExecuteReader();
                sqlDr.Read();
                context.Response.BinaryWrite((Byte[])sqlDr[3]);
                context.Response.End();

            }

            catch (Exception ex)
            {
                //Handle error If occured
            }
            finally
            {

                if (sqlDr != null && !sqlDr.IsClosed)
                {

                    sqlDr.Close(); //close SqlDataReader

                }

                conn.Close();//close database connection

            }
        }

    }
  
    public bool IsReusable
    {

        get
        {

            return false;

        }

    }

}

 Create 1 Procedures
Connect to ImageSave.aspx.cs for all data retrive from data base
SqlCommand sqlCmd = new SqlCommand("GetImageInfoFromDB", sqlConn);
CREATE PROCEDURE GetImageInfoFromDB

AS

BEGIN
 SELECT  id,SomeText,ImagePath,Image_Blob FROM dbo.Image_Binary
END



Create second procedure
Connect To ImageHandler.ashx for single data retrive

SqlCommand sqlCmd = new SqlCommand("GetImageFromDB", conn);

CREATE PROCEDURE GetImageFromDB(@id int)

AS

BEGIN



 SELECT  id,SomeText,ImagePath,Image_Blob FROM dbo.Image_Binary WHERE id = @id



END

After that  ImageHandler.ashx is called in ImageSave.aspx  datalist view/ grid view page
   <asp:DataList ID="Datalist1" runat="server"  Width="100px" RepeatColumns="1">
   <ItemTemplate>
   <img alt="Image" height="70px" src="<%# "ImageHandler.ashx?Id="+ Eval("id") %>" width="70px"/>
   </ItemTemplate>
      </asp:DataList>


 #SradhaWebCreations
Contact : +91-9040573923, +91-7008182025 http://sradhawebcreations.com/ http://sradhawebcreations.blogspot.in/ https://facebook.com/sradhawebcreations https://www.facebook.com/Sradhawebeducation/