Server Intellect
 
Home   Asp.Net Tutorials   What's New   Newsletter   More Resources
 
 
  Categories
Advanced Technologies
AJAX
Internet Browsers
Controls
Database
Email
Error Handling
File
Graphics
Website Navigation
Network
Performance
User Interface and Themes
Validation
Visual Web Developer
Web Services
XML
Suggest Tutorial


Navigator: Home - Tutorials - Database - Save image to database in ASP.NET 2.0(VB)
Save image to database in ASP.NET 2.0(VB)


ASP.NET Database Tutorial

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

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

We migrated our web sites to Server Intellect over one weekend and the setup was so smooth that we were up and running right away. They assisted us with everything we needed to do for all of our applications. With Server Intellect's help, we were able to avoid any headaches!

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>

Server Intellect assists companies of all sizes with their hosting needs by offering fully configured server solutions coupled with proactive server management services. Server Intellect specializes in providing complete internet-ready server solutions backed by their expert 24/365 proactive support team.

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

Download the Full Working Version of this Project written with Visual Studio.NET VB 2005 Here!

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

Looking for more ASP.NET Tutorials? Click Here!





 
  Developer Resources







Server Intellect Rocks