How To Save and Retrive Image into/from SQL Server Database by using ASP.Net


DATABASE TABLE:

WEBFORM DESIGN:

<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>

Image Name:<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
Select Image:<asp:FileUpload ID="FileUpload1" runat="server" />
<br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click"
Text="UploadImage" />
<br />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField HeaderText="ImageName" DataField="ImageName" />
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl='<%# "ImageHandler.ashx?Id=" + Eval("Id") %>' Height="150px" Width="150px" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

</div>
</form>
</body>
</html>

CONNECTION STRING:

first prepare connection string in web.config file under configuration tag  as follows:

<connectionStrings>
        <add name="ConnectionString" connectionString=”Data Source=server2;Initial Catalog=Venkat123;Persist Security Info=True;User ID=sa;Password=123″/>”
    </connectionStrings>

CODE BEHIND:

string connectionstring = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //getting existing data
            GetData();
        }

    }
    public void GetData()
    {
        SqlConnection con = new SqlConnection(connectionstring);
        SqlCommand cmd = new SqlCommand("select Id,ImageName from Image1", con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        da.Fill(dt);
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            //finding size of file
            int length = FileUpload1.PostedFile.ContentLength;
            //creating binary variable of above length
            byte[] imgbyte = new byte[length];
            //saving image in memory
            HttpPostedFile img = FileUpload1.PostedFile;
            //loading image into binary variable
            img.InputStream.Read(imgbyte, 0, length);
            string imgname = TextBox1.Text;
            SqlConnection con = new SqlConnection(connectionstring);
            con.Open();
            SqlCommand cmd = new SqlCommand("insert into Image1 (ImageName,ImageData) values (@imagename,@imagedata)", con);
            cmd.Parameters.Add("@imagename", SqlDbType.VarChar, 50).Value = imgname;
            cmd.Parameters.Add("@imagedata", SqlDbType.Image).Value = imgbyte;
            int count = cmd.ExecuteNonQuery();
            con.Close();
            if (count == 1)
            {
                GetData();
                TextBox1.Text = string.Empty;
            }
        }
    }

OUTPUTRESULT:

Image retrival code using handler file:

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

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

public class ImageHandler : IHttpHandler {
    string connectionstring = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
    public void ProcessRequest (HttpContext context) {
        string imageid = context.Request.QueryString["Id"];
        SqlConnection con = new SqlConnection(connectionstring);
        con.Open();
        SqlCommand cmd = new SqlCommand("select ImageData from Image1 where Id=" + imageid,con);
        SqlDataReader dr = cmd.ExecuteReader();
        dr.Read();
        context.Response.BinaryWrite((Byte[])dr[0]);
        con.Close();
        context.Response.End();
    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

Download Sample Code

Advertisements

5 thoughts on “How To Save and Retrive Image into/from SQL Server Database by using ASP.Net

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s