ASp.Net day

Micro blog



About Satalaj

www.satalaj.com

The best inline translator

Live lookup to see what asp.net developers are searching




asp net image upload


   In this article we will insert image into the Ms Sql server 2005 DataBase and we will show it using show button. 
This article is for begineers.  very very simple.

Use below url for discussion on this article
http://revenmerchantservices.com/post/2009/08/28/asp-net-image-upload-discussion.aspx 

e.g.
      

 

 

  1. After reading this article you will be

    1. Able to upload an Image into Ms Sql server 2005 Data base.
    2. Able to create image handler
    3. Display image in page.
  2. asp net image upload. Here we will use ASp.net and MS SQl Db.

    Below is the table schema used to store images. you need to execute it using Ms SQl query analyser.


    CREATE TABLE [dbo].[my_Images](
     [ImageID] [int] IDENTITY(1,1) NOT NULL,
     [Images] [varbinary](max) NOT NULL,
     CONSTRAINT [PK_my_Images] PRIMARY KEY CLUSTERED
    (
     [ImageID] ASC
    )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
    ) ON [PRIMARY]


  3. Add Asp.net File Upload control and one ASP.net button control in to your web page

     

    <body>

    <form id="form1" runat="server">

    <div>

    Upload your image:

    <asp:FileUpload ID="FileUpload1" runat="server" />

    <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Upload" />

    <br />

    <br />

    Show Image by Id:

    <asp:TextBox ID="TextBox1" runat="server">1</asp:TextBox>&nbsp;<asp:Button ID="Button2"

    runat="server" OnClick="Button2_Click" Text="show" />

    <br />

    <br />

    <asp:Image ID="Image1" runat="server" /></div>

    </form>

    </body>


     
    On button click we will upload the dat into MS SQl DB table My_Image. below is the code on click of button

  4.  

    using System;

    using System.Data;

    using System.Configuration;

    using System.Collections;

    using System.Web;

    using System.Web.Security;

    using System.Web.UI;

    using System.Web.UI.WebControls;

    using System.Web.UI.WebControls.WebParts;

    using System.Web.UI.HtmlControls;

    using System.Data.SqlClient;

    public partial class images : System.Web.UI.Page

    {

    protected void Page_Load(object sender, EventArgs e)

    {

    }

    protected void Button1_Click(object sender, EventArgs e)

    {

    byte []binaryImage = FileUpload1.FileBytes;

    string connectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["pppConnectionString"].ConnectionString;

    SqlConnection connection = new SqlConnection(connectionString);

    SqlCommand command = new SqlCommand("Insert into My_Images(Images) values(@image)",connection);command.Parameters.Add(

    new SqlParameter("@image", binaryImage));

    try

    {

    command.Connection.Open();

    int i = command.ExecuteNonQuery();

    }

    catch(Exception ex)

    {

    Response.Write(ex.Message);

    }

    }

    protected void Button2_Click(object sender, EventArgs e)

    {

    Image1.ImageUrl = (
    "~/Handler2.ashx?id="+TextBox1.Text);

    }

    }


    VB.Net code

      Imports System

    Imports System.Data

    Imports System.Configuration

    Imports System.Collections

    Imports System.Web

    Imports System.Web.Security

    Imports System.Web.UI

    Imports System.Web.UI.WebControls

    Imports System.Web.UI.WebControls.WebParts

    Imports System.Web.UI.HtmlControls

    Imports System.Data.SqlClient

    Public Partial Class images
        Inherits System.Web.UI.Page
       
       
        Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
           
        End Sub
       
        Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
           
            Dim binaryImage As Byte() = FileUpload1.FileBytes
            Dim connectionString As String = System.Web.Configuration.WebConfigurationManager.ConnectionStrings("pppConnectionString").ConnectionString
           
            Dim connection As New SqlConnection(connectionString)
            Dim command As New SqlCommand("Insert into My_Images(Images) values(@image)", connection)
           
            command.Parameters.Add(New SqlParameter("@image", binaryImage))
            Try
               
               
                command.Connection.Open()
               
                Dim i As Integer = command.ExecuteNonQuery()
            Catch ex As Exception
               
               
                   
                Response.Write(ex.Message)
               
            End Try
        End Sub
       
        Protected Sub Button2_Click(ByVal sender As Object, ByVal e As EventArgs)
           
            Image1.ImageUrl = ("~/Handler2.ashx?id=" & TextBox1.Text)
        End Sub
       
    End Class


     
  5. We will add new item GenericHandler to our web project  to our project which will handle the Image type. Below is Image handler code

  6.   <%@ WebHandler Language="C#" Class="Handler2" %>

    using System;

    using System.Web;

    using System.Data.SqlClient;

    using System.Data;

    using System.IO;

    public class Handler2 : IHttpHandler {

     

    public void ProcessRequest (HttpContext context)

    {

    context.Response.ContentType = "image/gif";

     

    string connectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["pppConnectionString"].ConnectionString;

    SqlConnection connection = new SqlConnection(connectionString);

    SqlCommand command = new SqlCommand("select images from my_images where imageid = @Id",connection);

    command.Parameters.Add(new SqlParameter("@Id",context.Request.QueryString["id"]));

     

    try

    {

    command.Connection.Open();

    SqlDataReader reader = command.ExecuteReader();

    DataTable dt = new DataTable();

    dt.Load(reader);

    byte[]binaryImage = (byte[])dt.Rows[0][0];

    reader.Close();

     

    context.Response.BinaryWrite(binaryImage);

     

    }

    catch(Exception ex)

    {

    throw ex;

    }

    finally

    {

    command.Connection.Close();

    }

     

    }

     

    public bool IsReusable {

    get {

    return false;

    }

    }

    }


    VB.Net Code

        <%@ WebHandler Language="C#" Class="Handler2" %>
    Imports System

    Imports System.Web

    Imports System.Data.SqlClient

    Imports System.Data

    Imports System.IO

    Public Class Handler2
        Implements IHttpHandler
       
       
       
        Public Sub ProcessRequest(ByVal context As HttpContext)
           
           
            context.Response.ContentType = "image/gif"
           
           
           
            Dim connectionString As String = System.Web.Configuration.WebConfigurationManager.ConnectionStrings("pppConnectionString").ConnectionString
           
            Dim connection As New SqlConnection(connectionString)
           
            Dim command As New SqlCommand("select images from my_images where imageid = @Id", connection)
           
            command.Parameters.Add(New SqlParameter("@Id", context.Request.QueryString("id")))
           
           
           
            Try
               
               
                command.Connection.Open()
               
                Dim reader As SqlDataReader = command.ExecuteReader()
               
                Dim dt As New DataTable()
               
                dt.Load(reader)
               
                Dim binaryImage As Byte() = DirectCast(dt.Rows(0)(0), Byte())
               
                reader.Close()
               
               
               
                   
                   
                   
                context.Response.BinaryWrite(binaryImage)
            Catch ex As Exception
               
               
               
                   
                Throw ex
            Finally
               
               
               
                   
                command.Connection.Close()
               
               
               
            End Try
        End Sub
       
       
       
        Public ReadOnly Property IsReusable() As Boolean
           
            Get
               
                   
                Return False
            End Get
        End Property
       
       
    End Class



    Use below url for discussion on this article
    http://revenmerchantservices.com/post/2009/08/28/asp-net-image-upload-discussion.aspx 

    -Satalaj