JEYAGANESH

JEYAGANESH
Software Developer

Tuesday, 19 June 2012

how to insert images into database and how to retrieve and bind images to gridview using asp.net (or) save and Retrieve images from database using asp.net

Introduction

Here I will explain how insert and retrieve images from database and how to bind images to gridview using asp.net
TableName : image_upload

Column Name
Data Type
Allow Nulls
Id
Int
Yes
imagesimageYes

After that Design your aspx page like this 


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    Image
        <asp:FileUpload ID="FileUpload1" runat="server" /><br />
        <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
    </div>


<div>
<asp:GridView ID="gvImages" CssClass="Gridview" runat="server" AutoGenerateColumns="False"
HeaderStyle-BackColor="#7779AF" HeaderStyle-ForeColor="white">
<Columns>
<asp:BoundField HeaderText = "id" DataField="id" />
<asp:TemplateField HeaderText="Image Id">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl='<%# "ImageHandler.ashx?ImID="+ Eval("id") %>' Height="150px" Width="150px"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>

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



web.config
------------


<connectionStrings>
        <add name="mmConnectionString" connectionString="server=SAMSUNG\SQLEXPRESS;Integrated Security=true;database=sample;" providerName="System.Data.SqlClient"/>
    </connectionStrings>



default.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;
namespace WebApplication4
{
   
    public partial class _Default : System.Web.UI.Page
    {
        string strcon = ConfigurationManager.ConnectionStrings["mmConnectionString"].ConnectionString;
        protected void Page_Load(object sender, EventArgs e)
        {
           

if (!IsPostBack)
{
BindGridData();
}
        }
private void BindGridData()
{
SqlConnection connection = new SqlConnection(strcon);
SqlCommand command = new SqlCommand("SELECT images,ID from [Image]", connection);
SqlDataAdapter daimages = new SqlDataAdapter(command);
DataTable dt = new DataTable();
daimages.Fill(dt);
gvImages.DataSource = dt;
gvImages.DataBind();
gvImages.Attributes.Add("bordercolor", "black");
}

        protected void Button1_Click(object sender, EventArgs e)
        {
            if (FileUpload1.HasFile)
            {
                int image_length = FileUpload1.PostedFile.ContentLength;
                byte[] imgtype=new byte[image_length];
                HttpPostedFile img = FileUpload1.PostedFile;
                img.InputStream.Read(imgtype, 0, image_length);
                SqlConnection con = new SqlConnection(strcon);
                con.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.CommandText = "insert into image_upload values(1,'"+imgtype+"')";
                cmd.CommandType = CommandType.Text;
                cmd.Connection = con;
                int count = cmd.ExecuteNonQuery();
                con.Close();
                if (count == 1)
                {

                     BindGridData();
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "alertmessage", "alert('image inserted successfully')", true);
                }
            }
        }
    }
}





handler.ashx.cs
---------------


string strcon = ConfigurationManager.AppSettings["mmConnectionString"].ToString();
public void ProcessRequest(HttpContext context)
{
string imageid = context.Request.QueryString["ImID"];
SqlConnection connection = new SqlConnection(strcon);
connection.Open();
SqlCommand command = new SqlCommand("select Images from image_upload where ID=" + imageid, connection);
SqlDataReader dr = command.ExecuteReader();
dr.Read();
context.Response.BinaryWrite((Byte[])dr[0]);
connection.Close();
context.Response.End();
}

1 comment: