Tutorial RSS
 
DB Tutorials Server Intellect Cloud Hosting
Navigator: Home - Advanced - Save image to database in ASP.NET 2.0(VB)

Save image to database in ASP.NET 2.0(VB)

This tutorial will show you how to save image to a SQL database using ASP.NET and VB.NET.

Server Intellect offers Windows Hosting Dedicated Servers at affordable prices. I'm very pleased!


Looking for the C#.NET 2005 Version? Click Here!

Looking for more ASP.NET Tutorials? Click Here!

This tutorial need the sample database provided by MS SQL.

Database:Northwind Table:Categories

Please modify the connectionstring based on the environment of your computer. The sample as below:
string strConnectionString = "Data Source=dev005;Initial Catalog=Northwind;User ID=sa;password=1234";

Then, you will need to import the System.IO and System.Data.SqlClient namespace.

The System.IO namespace contains the FileInfo and FileStream Classes. They transfer image or file to stream and save to database.

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

By clicking button of 'Upload', we will save the selected image into database.

By clicking button of 'Show latest Image', the application will show the latest image from database on the page of Default.aspx

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim imageInfo As FileInfo = New FileInfo(Me.File1.Value.Trim())
If imageInfo.Exists() = False Then
Me.RegisterClientScriptBlock("alertMsg", "<script>alert('please select one image file.');</script>")
Else
Select Case (imageInfo.Extension.ToUpper())
Case ".JPG" : UpLoadImageFile(Me.File1.Value.Trim())
Case ".GIF" : UpLoadImageFile(Me.File1.Value.Trim())
Case ".BMP" : UpLoadImageFile(Me.File1.Value.Trim())
'default: RegisterClientScriptBlock("alertMsg", "<script>alert('file type error.');</script>")
End Select
End If
End Sub

Private Sub UpLoadImageFile(ByVal info As String)
Dim objConn As SqlConnection
Dim objCom As SqlCommand
Try
Dim imagestream As FileStream = New FileStream(info, FileMode.Open)
Dim data() As Byte
ReDim data(imagestream.Length - 1)
imagestream.Read(data, 0, imagestream.Length)

imagestream.Close()
objConn = New SqlConnection(strConnectionString)
objCom = New SqlCommand("insert into Categories(CategoryName,Picture)values(@CategoryName,@Picture)", objConn)

Dim categorynameParameter As SqlParameter = New SqlParameter("@CategoryName", SqlDbType.NVarChar)
If Me.txtFileName.Text.Trim().Equals("") Then
categorynameParameter.Value = "Default"
Else
categorynameParameter.Value = Me.txtFileName.Text.Trim()
End If
objCom.Parameters.Add(categorynameParameter)

Dim pictureParameter As SqlParameter = New SqlParameter("@Picture", SqlDbType.Image)
pictureParameter.Value = data
objCom.Parameters.Add(pictureParameter)
objConn.Open()
objCom.ExecuteNonQuery()
objConn.Close()
Catch ex As Exception
Throw New Exception(ex.Message)
objConn.Close()
End Try
End Sub

Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim objConn As SqlConnection
Try
objConn = New SqlConnection(strConnectionString)
Dim objCom As SqlCommand = New SqlCommand("select * from Categories order by CategoryID DESC", objConn)
objConn.Open()
Dim MyReader As SqlDataReader = objCom.ExecuteReader(CommandBehavior.CloseConnection)
If MyReader.HasRows = True Then
MyReader.Read()
Me.Response.ContentType = "text/HTML"
'Dim Msg() As Byte
'Msg = System.Text.Encoding.Default.GetBytes(MyReader("Picture").ToString())
Me.Response.BinaryWrite(MyReader.Item("Picture"))
Else
RegisterClientScriptBlock("alertMsg", "<script>alert('No Image.');</script>")
End If
MyReader.Close()
objConn.Close()
Catch ex As Exception
Throw New Exception(ex.Message)
End Try
End Sub


Need help with Windows Dedicated Hosting? Try Server Intellect. I'm a happy customer!


The front end Default.aspx page looks something like this:

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_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 id="Head1" runat="server">
<title>Default</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<fieldset>
<legend>Upload image to database</legend>
<table>
<tr>
<td style="width: 464px">
File Name:<asp:TextBox ID="txtFileName" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td style="width: 464px">
<input id="File1" runat="server" type="file" /></td>
</tr>
<tr>
<td style="width: 464px">
<asp:Button ID="Button1" runat="server" Text="Upload" OnClick="Button1_Click" /></td>
</tr>

</table>
<br/>
<table>
<tr>
<td style="width: 464px">
<asp:Button ID="Button2" runat="server" Text="show latest Image" OnClick="Button2_Click" /></td>
</tr>

</table>
</fieldset>

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

The flow for the code behind page is as follows.

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

Partial Class _Default
Inherits System.Web.UI.Page

Dim strConnectionString As String = "Data Source=dev005;Initial Catalog=Northwind;User ID=sa;password=1234"

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim imageInfo As FileInfo = New FileInfo(Me.File1.Value.Trim())
If imageInfo.Exists() = False Then
Me.RegisterClientScriptBlock("alertMsg", "<script>alert('please select one image file.');</script>")
Else
Select Case (imageInfo.Extension.ToUpper())
Case ".JPG" : UpLoadImageFile(Me.File1.Value.Trim())
Case ".GIF" : UpLoadImageFile(Me.File1.Value.Trim())
Case ".BMP" : UpLoadImageFile(Me.File1.Value.Trim())
'default: RegisterClientScriptBlock("alertMsg", "<script>alert('file type error.');</script>")
End Select
End If
End Sub

Private Sub UpLoadImageFile(ByVal info As String)
Dim objConn As SqlConnection
Dim objCom As SqlCommand
Try
Dim imagestream As FileStream = New FileStream(info, FileMode.Open)
Dim data() As Byte
ReDim data(imagestream.Length - 1)
imagestream.Read(data, 0, imagestream.Length)

imagestream.Close()
objConn = New SqlConnection(strConnectionString)
objCom = New SqlCommand("insert into Categories(CategoryName,Picture)values(@CategoryName,@Picture)", objConn)

Dim categorynameParameter As SqlParameter = New SqlParameter("@CategoryName", SqlDbType.NVarChar)
If Me.txtFileName.Text.Trim().Equals("") Then
categorynameParameter.Value = "Default"
Else
categorynameParameter.Value = Me.txtFileName.Text.Trim()
End If
objCom.Parameters.Add(categorynameParameter)

Dim pictureParameter As SqlParameter = New SqlParameter("@Picture", SqlDbType.Image)
pictureParameter.Value = data
objCom.Parameters.Add(pictureParameter)
objConn.Open()
objCom.ExecuteNonQuery()
objConn.Close()
Catch ex As Exception
Throw New Exception(ex.Message)
objConn.Close()
End Try
End Sub

Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim objConn As SqlConnection
Try
objConn = New SqlConnection(strConnectionString)
Dim objCom As SqlCommand = New SqlCommand("select * from Categories order by CategoryID DESC", objConn)
objConn.Open()
Dim MyReader As SqlDataReader = objCom.ExecuteReader(CommandBehavior.CloseConnection)
If MyReader.HasRows = True Then
MyReader.Read()
Me.Response.ContentType = "text/HTML"
'Dim Msg() As Byte
'Msg = System.Text.Encoding.Default.GetBytes(MyReader("Picture").ToString())
Me.Response.BinaryWrite(MyReader.Item("Picture"))
Else
RegisterClientScriptBlock("alertMsg", "<script>alert('No Image.');</script>")
End If
MyReader.Close()
objConn.Close()
Catch ex As Exception
Throw New Exception(ex.Message)
End Try
End Sub
End Class



Looking for the C#.NET 2005 Version? Click Here!

Looking for more ASP.NET Tutorials? Click Here!

I just signed up at Server Intellect and couldn't be more pleased with my Windows Server! Check it out and see for yourself.


Download Project Source - Enter your Email to be emailed a link to download the Full Source Project used in this Tutorial!



100% SPAM FREE! We will never sell or rent your email address!