Thursday, October 11, 2012

Insert and Retrieve Image from Database (Sql Server) in .net

In this Example I will show you how to insert and fetch Image Directly from Database.

Step 1. First We will create Table.




Step 2.
Now code to insert image in Database
SaveImage.aspx

Design.

<form id="form1" runat="server">
    <asp:FileUpload ID="FileUpload1" runat="server" />
    <asp:Button ID="Button1" runat="server"
        Text="Button" onclick="Button1_Click" />
</form>


Code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
public partial class saveimageinbinary : System.Web.UI.Page
{
    SqlConnection conn;
    string s = ConfigurationManager.ConnectionStrings["imageconverter"].ConnectionString.ToString();
    protected void Page_Load(object sender, EventArgs e)
    {
        conn = new SqlConnection(s);
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        StartUpLoad();
    }
    private void StartUpLoad()
    {

        //get the image file that was posted (binary format)

        byte[] theImage = new byte[FileUpload1.PostedFile.ContentLength];
        HttpPostedFile Image = FileUpload1.PostedFile;
        Image.InputStream.Read(theImage, 0, (int)FileUpload1.PostedFile.ContentLength);
        int length = theImage.Length; //get the length of the image
        string fileName = FileUpload1.FileName.ToString(); //get the file name of the posted image
        string type = FileUpload1.PostedFile.ContentType; //get the type of the posted image
        int size = FileUpload1.PostedFile.ContentLength; //get the size in bytes that
        if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != "")
        {
            //Call the method to execute Insertion of data to the Database
            ExecuteInsert(theImage, fileName, length);
            Response.Write("Save Successfully!");
        }
    }

    private void ExecuteInsert(byte[] Image, string Name, int length)
    {
        
        string sql = "INSERT INTO TblImages (Image, ImageName) VALUES "
       + " (@img,@imgname)";

       // SqlCommand cmd = new SqlCommand(sql,conn);

       // conn.Open();
       //// cmd.ExecuteNonQuery();
       
        try
        {
            conn.Open();
            SqlCommand cmd = new SqlCommand(sql, conn);
            SqlParameter[] param = new SqlParameter[4];

            param[0] = new SqlParameter("@img", SqlDbType.Image, length);

            param[1] = new SqlParameter("@type", SqlDbType.NVarChar, 50);
            param[2] = new SqlParameter("@imgsize", SqlDbType.BigInt, 9999);
            param[3] = new SqlParameter("@imgname", SqlDbType.NVarChar, 50);

            param[0].Value = Image;

            param[1].Value = Type;
            param[2].Value = Size;
            param[3].Value = Name;

            for (int i = 0; i < param.Length; i++)

            {
                cmd.Parameters.Add(param[i]);
            }

            cmd.CommandType = CommandType.Text;

            cmd.ExecuteNonQuery();
        }
        catch (System.Data.SqlClient.SqlException ex)
        {
            string msg = "Insert Error:";
            msg += ex.Message;
            throw new Exception(msg);
        }
        finally
        {
        
            conn.Close();
        }
    }
}

Step 3
Fetch Image from Database.
Here I am using Handler.ashx page to retrieve image.
ShowImage.aspx


Design.


 <div>
 <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true"             onselectedindexchanged="DropDownList1_SelectedIndexChanged">
        </asp:DropDownList><br />
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label><br />
        <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label><br />
</div>

Code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public partial class showbinaryimage : System.Web.UI.Page
{
    SqlConnection connection;
    string s = ConfigurationManager.ConnectionStrings["imageconverter"].ConnectionString.ToString();
    private void BindFileNames()
    {

        DataTable dt = new DataTable();
      //  SqlConnection connection = new SqlConnection(GetConnectionString());

        try
        {
            connection.Open();
            string sqlStatement = "SELECT * FROM TblImages";
            SqlCommand sqlCmd = new SqlCommand(sqlStatement, connection);
            SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);

            sqlDa.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                DropDownList1.DataSource = dt;
                DropDownList1.DataTextField = "ImageName"; // the items to be displayed in the list items
                DropDownList1.DataValueField = "Id"; // the id of the items displayed
                DropDownList1.DataBind();
            }
        }
        catch (System.Data.SqlClient.SqlException ex)
        {
            string msg = "Fetch Error:";
            msg += ex.Message;
            throw new Exception(msg);
        }
        finally
        {
            connection.Close();
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            BindFileNames();
            connection = new SqlConnection(s);
        }
    }
    public string GetConnectionString()
    {
        //sets the connection string from your web config file "ConnString" is the name of your Connection String
        return System.Configuration.ConfigurationManager.ConnectionStrings["imageconverter"].ConnectionString;
    }
    private void GetImageInfo(string id)
    {
        
        string sql = "SELECT * FROM TblImages WHERE Id = @id";

        SqlCommand cmd = new SqlCommand(sql, connection);
        cmd.Parameters.AddWithValue("@id", id);
        connection.Open();

        SqlDataReader reader = cmd.ExecuteReader();
        reader.Read();

        //Get Image Information
        Label1.Text = reader["ImageName"].ToString();
        reader.Close();
        connection.Close();
    }
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (DropDownList1.SelectedIndex > 0)
        {
            //Set the ImageUrl to the path of the handler with the querystring value
            Image1.ImageUrl = "Handler.ashx?id=" + DropDownList1.SelectedItem.Value;
            //call the method to get the image information and display it in Label Control
            GetImageInfo(DropDownList1.SelectedItem.Value);
        }
    }
   
}


Handler.ashx



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

using System;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using System.IO;
using System.Collections.Specialized;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
public class Handler : IHttpHandler {

    public string GetConnectionString()
    {
        //sets the connection string from your web config file "ConnString" is the name of your Connection String
        return System.Configuration.ConfigurationManager.ConnectionStrings["imageconverter"].ConnectionString;
    }
     public void ProcessRequest(HttpContext context)
    {
        string id = context.Request.QueryString["id"]; //get the querystring value that was pass on the ImageURL (see GridView MarkUp in Page1.aspx)

        if (id != null)
        {
           
            MemoryStream memoryStream = new MemoryStream();
            SqlConnection connection = new SqlConnection(GetConnectionString());
            string sql = "SELECT * FROM TblImages WHERE Id = @id";
       
            SqlCommand cmd = new SqlCommand(sql, connection);
            cmd.Parameters.AddWithValue("@id", id);
            connection.Open();

            SqlDataReader reader = cmd.ExecuteReader();
            reader.Read();

            //Get Image Data
            byte[] file = (byte[])reader["Image"];

            reader.Close();
            connection.Close();
            memoryStream.Write(file, 0, file.Length);
            context.Response.Buffer = true;
            context.Response.BinaryWrite(file);
            memoryStream.Dispose();

        }
    }

    public bool IsReusable {
        get {
            return false;
        }
    }
}