Tutorial RSS
 
Navigator: Home - Advanced - Save image to database in ASP.NET 2.0(C#)

Save image to database in ASP.NET 2.0(C#)

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

We chose Server Intellect for its dedicated servers, for our web hosting. They have managed to handle virtually everything for us, from start to finish. And their customer service is stellar.


Looking for the VB.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.

using System.Data.SqlClient;
using System.IO;
using 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 void Button1_Click(object sender, EventArgs e)
{
FileInfo imageInfo = new FileInfo(File1.Value.Trim());

if (!imageInfo.Exists)
this.RegisterClientScriptBlock("alertMsg", "<script>alert('please select one image file.');</script>");
else
{
switch (imageInfo.Extension.ToUpper())
{
case ".JPG": this.UpLoadImageFile(imageInfo); break;
case ".GIF": this.UpLoadImageFile(imageInfo); break;
case ".BMP": this.UpLoadImageFile(imageInfo); break;
default: this.RegisterClientScriptBlock("alertMsg", "<script>alert('file type error.');</script>"); break;
}
}
}

private void UpLoadImageFile(FileInfo info)
{
SqlConnection objConn = null;
SqlCommand objCom = null;
try
{
byte[] content = new byte[info.Length];
FileStream imagestream = info.OpenRead();
imagestream.Read(content, 0, content.Length);
imagestream.Close();

objConn = new SqlConnection(strConnectionString);
objCom = new SqlCommand("insert into Categories(CategoryName,Picture)values(@CategoryName,@Picture)", objConn);

SqlParameter categorynameParameter = new SqlParameter("@CategoryName", SqlDbType.NVarChar);
if (this.txtFileName.Text.Trim().Equals(""))
categorynameParameter.Value = "Default";
else
categorynameParameter.Value = this.txtFileName.Text.Trim();
objCom.Parameters.Add(categorynameParameter);

SqlParameter pictureParameter = new SqlParameter("@Picture", SqlDbType.Image);
pictureParameter.Value = content;
objCom.Parameters.Add(pictureParameter);

objConn.Open();
objCom.ExecuteNonQuery();
objConn.Close();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
objConn.Close();
}
}

protected void Button2_Click(object sender, EventArgs e)
{
SqlConnection objConn = null;
try
{
objConn = new SqlConnection(strConnectionString);

SqlCommand Command = new SqlCommand("select * from Categories order by CategoryID DESC", objConn);
objConn.Open();
SqlDataReader MyReader = Command.ExecuteReader(CommandBehavior.CloseConnection);

if (MyReader.HasRows == true)
{
MyReader.Read();

Response.ContentType = "text/HTML";
Response.BinaryWrite((byte[])MyReader["Picture"]);
}
else
{
this.RegisterClientScriptBlock("alertMsg", "<script>alert('No Image.');</script>");
} MyReader.Close();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}

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>

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


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 VB.NET 2005 Version? Click Here!

Looking for more ASP.NET Tutorials? Click Here!

We moved our web sites to Server Intellect and have found them to be incredibly professional. Their setup is very easy and we were up and running in no time.


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!

411asp.net123aspxDotNetFreaksServer Intellect