Home > ASP.Net > Insert and Display Image from Database

Insert and Display Image from Database


Hi

try this example to Insert and Display Image from Database in Gridview

Database Script:

CREATE DATABASE [Employee]
GO
USE [Employee]
GO
CREATE TABLE EmpDetails
(
empid int IDENTITY NOT NULL,
empname varchar(20),
empimg image
)

Default.aspx

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

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

<html xmlns="<a href="http://www.w3.org/1999/xhtml">http://www.w3.org/1999/xhtml</a>">
<head runat="server">
    <title>Save Retrieve Images</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
        <asp:Label ID="lblEmpName" runat="server" Text="Employee Name"></asp:Label>
&nbsp;&nbsp;&nbsp;&nbsp;
        <asp:TextBox ID="txtEName" runat="server"></asp:TextBox>
        <br />
        <asp:Label ID="lblImage" runat="server" Text="Employee Image"></asp:Label>
&nbsp;&nbsp;&nbsp;&nbsp;
        <asp:FileUpload ID="imgUpload" runat="server" />
        <br />
        <br />
        <asp:Button ID="btnSubmit" runat="server" onclick="btnSubmit_Click"
            Text="Submit" />
        <asp:Label ID="lblResult" runat="server" ForeColor="#0066FF"></asp:Label>
    <br />
    <hr />
  
   <asp:Image ID="Image1" style="width:200px" Runat="server" />
    </div>
    </form>
</body>
</html>

Default.asp.cs

using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        SqlConnection connection = null;
        try
        {
            FileUpload img = (FileUpload)imgUpload;
            Byte[] imgByte = null;
            if (img.HasFile && img.PostedFile != null)
            {
                //To create a PostedFile
                HttpPostedFile File = imgUpload.PostedFile;
                //Create byte Array with file len
                imgByte = new Byte[File.ContentLength];
                //force the control to load data in array
                File.InputStream.Read(imgByte, 0, File.ContentLength);
            }
            // Insert the employee name and image into db
            string conn = ConfigurationManager.ConnectionStrings["EmployeeConnString"].ConnectionString;
            connection = new SqlConnection(conn);

            connection.Open();
            string sql = "INSERT INTO EmpDetails(empname,empimg) VALUES(@enm, @eimg) SELECT @@IDENTITY";
            SqlCommand cmd = new SqlCommand(sql, connection);
            cmd.Parameters.AddWithValue("@enm", txtEName.Text.Trim());
            cmd.Parameters.AddWithValue("@eimg", imgByte);
            int id = Convert.ToInt32(cmd.ExecuteScalar());
            lblResult.Text = String.Format("Employee ID is {0}", id);

            // Display the image from the database
            Image1.ImageUrl = "~/ShowImage.ashx?id=" + id;
        }
        catch
        {
            lblResult.Text = "There was an error";
        }
        finally
        {
            connection.Close();
        }

    }
}

In order to display the image on the page, we will create an Http handler. To do so, right click project > Add New Item > Generic Handler > ShowImage.ashx. Add the code shown below to the handler.

ShowImage.ashx

<%@ WebHandler Language="C#" Class="ShowImage" %></span></div>
<div><span style="font-size: x-small;">using System;
using System.Configuration;
using System.Web;
using System.IO;
using System.Data;
using System.Data.SqlClient;</span></div>
<span style="font-size: x-small;">public class ShowImage : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
       Int32 empno;
       if (context.Request.QueryString["id"] != null)
            empno = Convert.ToInt32(context.Request.QueryString["id"]);
       else
            throw new ArgumentException("No parameter specified");

       context.Response.ContentType = "image/jpeg";
       Stream strm = ShowEmpImage(empno);
       byte[] buffer = new byte[4096];
       int byteSeq = strm.Read(buffer, 0, 4096);

       while (byteSeq > 0)
       {
           context.Response.OutputStream.Write(buffer, 0, byteSeq);
           byteSeq = strm.Read(buffer, 0, 4096);
       }       
       //context.Response.BinaryWrite(buffer);
    }

    public Stream ShowEmpImage(int empno)
    {
        string conn = ConfigurationManager.ConnectionStrings["EmployeeConnString"].ConnectionString;
        SqlConnection connection = new SqlConnection(conn);
        string sql = "SELECT empimg FROM EmpDetails WHERE empid = @ID";
        SqlCommand cmd = new SqlCommand(sql,connection);
        cmd.CommandType = CommandType.Text;
        cmd.Parameters.AddWithValue("@ID", empno);
        connection.Open();
        object img = cmd.ExecuteScalar();
        try
        {
            return new MemoryStream((byte[])img);
        }
        catch
        {
            return null;
        }
        finally
        {
            connection.Close();
        }
    }

</span>

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

ViewImage.aspx

<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False"
            CellPadding="4" DataKeyNames="empid" DataSourceID="SqlDataSource1" ForeColor="#333333">
            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <Columns>
                <asp:BoundField DataField="empid" HeaderText="Id" InsertVisible="False" ReadOnly="True"
                    SortExpression="empid" />
                <asp:BoundField DataField="empname" HeaderText="Employee Name" SortExpression="empname" />
                <asp:TemplateField HeaderText="Employee Image" SortExpression="empimg">
                
                    <ItemTemplate>
                        <asp:Image ID="Image1" runat="server" Height="107px" ImageUrl='<%# Eval("empid", "~/ShowImage.ashx?id={0}") %>'
                            Width="108px" />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
            <RowStyle BackColor="#EFF3FB" />
            <EditRowStyle BackColor="#2461BF" />
            <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <AlternatingRowStyle BackColor="White" />
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:EmployeeConnString %>"
            ProviderName="<%$ ConnectionStrings:EmployeeConnString.ProviderName %>" SelectCommand="SELECT * FROM [EmpDetails]">
        </asp:SqlDataSource>

Hope it helps

Good Luck
 
 

 

Advertisements
  1. December 25, 2008 at 8:05 pm

    Awesome the whole package
    thanks

  2. yasserzaid
    December 25, 2008 at 9:23 pm

    Thanks Rick for your comment

    Hope it helps you

    Best Regards,

    YZ

  3. December 26, 2008 at 4:28 am

    Greate job I’ve been looking for something like this for months

    allso I’ve been playing with the new image generation
    tool take a look at my post on this forum and see if you can
    fix the problem I’m having with it and maybe you could do an articale
    http://forums.asp.net/t/1363105.aspx

    i’m a novice learning along the way articales like this one are a big help I’ve allso used this code with varbinary I allso set the Image url in the Image tag on the aspx page
    I’ll keep an eye on this site for any other good stuff
    Thanks keep up the good work

  4. yasserzaid
    December 26, 2008 at 11:51 am

    Oh thank ypu Rick for you comment and i hope my blog can help you and help others also

    and i will try to post an example to explain how to insert and display image path from database and display it in Gridview

    Good Luck

    Best Regards,

    YZ

  5. Laurie
    January 26, 2009 at 9:49 am

    This seems so close to what I want to do ….

    I have the addresses of the pics I want to put up as thumbnails in to a table and access the table to present them as dataview – I’d really like to have them as thumbnails and let a click present them as a full pic in a new window…….

    I’m afraid I feel comfortable at the SQL Server end – but am totally new with VB and Visual Studio.

    OKnever having ‘posted’ anything in my life, forgive me if I’m in the wrong place ……..

    the code in the asp looks like this:

    <asp:SqlDataSource ID="SqlDataSource2" runat="server"
    ConnectionString="”
    SelectCommand=”sp_GetPhotoURLs” SelectCommandType=”StoredProcedure”>

  6. tsatsaa
    May 29, 2011 at 5:43 am

    Thank you very much. Good luck!

  7. yasserzaid
    May 29, 2011 at 8:21 am

    @tsatsaa :- you are welcome

  1. No trackbacks yet.

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

%d bloggers like this: