Sunday, November 11, 2012

How to Insert an image into SQL data base using asp.net with vb.net

Introduction:

This article describes how to store an images into SQL database using ASP.net with vb.net coding as step by step guide. Most likely we are struggling while creating an application with handling images; here the simple steps are given. You can easily getting following details even you are beginner of dot net.

  
1.       Now we are going to create a Web application using ASP.net.
2.       Here I am using visual studio 2008 and SQL 2005.
3.       First thing you create a database for storing images like that “imgdbs.mdf”. Then  create a table That contain following field

a.      ID                     (integer)
b.     Img                  (image)
c.     Img_name   (varchar)
d.    Img_type     (varchar)

Table description:

The “ID” field refers unique identification of images. We can set it as a Primary key. After then “Img” field can hold the image data as byte format so it can be Image. The field of “Img_name” contains the name of storing image, and finally “Img_type” which uses for when we retrieving an image from database the type should be need.

Your Table should be like this


The design for client side:

Probably File Upload controls are used to getting a file from client system. So here also I use that same control.


·         Open a new web application in visual basic coding; set the name as “uploading images”.·         Open a default.aspx you can change the name “Default” whatever you want.·         Add the fileupload control to your design page.·         Then add one Button control set the name as “Upload”


Your Markup code may look like this
<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="upload_images._Default" %>

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

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>INSERTION OF IMAGE</title>
    <style type="text/css">
        .style1
        {
            width: 80%;
        }
    </style>
</head>
<body bgcolor="#99ccff">
    <form id="form1" runat="server">
    <div>
   
        <asp:Panel ID="Panel1" runat="server" Height="144px">
            <table align="center" class="style1">
                <tr>
                    <td align="center">
                        <b>This web page for sample of inserting image into SQL database using Asp.net with
                        vb.net codings</b>
                        <br />                       
                        <asp:FileUpload ID="FileUpload1" runat="server" />
                    </td>
                </tr>
                <tr>
                    <td align="center">
                        <asp:Button ID="Button1" runat="server" Text="Upload" />
                        <br />
                        <asp:Label ID="Label1" runat="server"></asp:Label>
                    </td>
                </tr>
            </table>
        </asp:Panel>
   
    </div>
    </form>
</body>
</html>

Now you completing the web site simple design seem like this


·         Double click that the Upload button or press ‘F7’ which brings you to on server side code window.


Server side codes in vb.net

Imports System.Data.SqlClient
Imports System.Data
Imports System

Partial Public Class _Default
    Inherits System.Web.UI.Page

    Dim dr As SqlClient.SqlDataReader
    Dim command As SqlClient.SqlCommand
    Dim con As New SqlClient.SqlConnection("Connection string")
    'Here don’t forgot to set the connection string

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
        Dim fileName, fileType As String
        Dim namePosition As Int16
        Dim idvalue As Integer = 1
  'Here I am set the idvalue =1 for it is defalut value and id numbers are                         ‘starts from 1
        Dim stream As IO.Stream
        'Provides a generic view of a sequence of bytes.

        con.Open()
        command = New SqlClient.SqlCommand("select max(id) from images", con)
        dr = command.ExecuteReader
            'Here the database returns the maximum of ID number. Then only we can increment that for set unique ID for each images
'First time inserting an image the database returns the ID value as NULL; so we should ignore that when ID value as become as ‘1’ will be placed
        If dr.Read Then
            If dr.IsDBNull(0) Then
                MsgBox("itis Nullable")
            Else
                idvalue = CInt(dr.GetValue(0))
                idvalue += 1
            End If
           
        End If
        con.Close()

        stream = FileUpload1.PostedFile.InputStream

        If FileUpload1.HasFile = Nothing Then
            Label1.ForeColor = Drawing.Color.Red
            Label1.Text = "Plese select The Image file"
'The fileUpload control does not contains any file when it will be displayed!
        Else
            Dim uploadedFile(stream.Length) As Byte
‘Byte represents an 8-bit unsigned integer. Here the content of the image will begetting as Byte format
            stream.Read(uploadedFile, 0, stream.Length)
            namePosition = FileUpload1.PostedFile.FileName.LastIndexOf("\") + 1
           
            fileName = FileUpload1.PostedFile.FileName.Substring(namePosition)
            fileType = FileUpload1.PostedFile.ContentType

            Try
                con.Open()
                command = New SqlClient.SqlCommand("INSERT INTO images (ID,img,img_name,img_type) Values(@idvalue,@Image,@Image_name,@Image_type )", con)

                command.Parameters.Add("@idvalue", SqlDbType.Int).Value = idvalue

                command.Parameters.Add("@Image_type", SqlDbType.NVarChar, 50).Value = fileType

                command.Parameters.Add("@Image", SqlDbType.Image, uploadedFile.Length).Value = uploadedFile

                command.Parameters.Add("@Image_name", SqlDbType.NVarChar, 50).Value = fileName

                command.ExecuteNonQuery()
                Label1.ForeColor = Drawing.Color.Green
                Label1.Text = "Your image uploaded sucessfully"

                con.Close()
            Catch ex As Exception
                Label1.ForeColor = Drawing.Color.Red
                Label1.Text = ex.Message.ToString()
            End Try
        End If

    End Sub

After that completing above process Now you can finish that the project.


when you click the choose button the open dialog box will be open


Now your image uploaded successfully


Inserted images that seem as Binary data format


No comments:

Post a Comment