Save image to Sql Server database in ASP.NET

No.of Views3077
Bookmarked0 times
Downloads 
Votes0
By  RRaveen   On  15 Feb 2010 22:02:47
Tag : ASP.NET , How to
Save image to Sql Server database in ASP.NET
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Introduction

Most of the time we need to play with images in asp.net in any kind of web sites. Since we need to save

photos, icons and etc to file system or database. Images saving process to file system is not an issue or not complicated job. But when we save to database we would take care few points and proper way to add to the database.

Technologies:
ASP.NET


Language:
C# and T-SQL


Prerequisite:
Visual Studio 2008, SQL Server 2005

Implementation

1. When we use the SQL server database to save image we need to use the "Image" Data Type.

2. If you use the Image data type, you need to send data as binary values as image content.

To this first we should design database to save the images.

Then we need to design webpage to pickup image from the client and read byte by byte and save to database.

Page look like followings figure.

We have page now, next start to write code to read using binary reader. Add code within the Upload button click event.

{codecitation class="brush:csharp; gutter: true;" width="500px"}

protected void btnUpload_Click(object sender, EventArgs e)
{
if (fleuploadImage.HasFile)
{
string fileName = fleuploadImage.PostedFile.FileName;

byte[] data = null;
int dataLength = 0;
dataLength = fleuploadImage.PostedFile.ContentLength;
using (BinaryReader reader = new BinaryReader(fleuploadImage.PostedFile.InputStream))
{
data = reader.ReadBytes(dataLength);
}
if (data.Length > 0)
{
ImageUtilityDA imageUtilityDA = new ImageUtilityDA();
bool result = imageUtilityDA.AddImageToDB(data, new Random().Next(1000));
if (result)
{
lblMessage.Text = "Your have succesfully update your photo to server";
}
}
}
}

{/codecitation}

Above method just read file using binaryReader which user picked up picture. After he select the file we need to get length of the posted file. Based on file we can read file content and make byte array.Finally pass the byte data to another method to save into the database.

{codecitation class="brush:csharp; gutter: true;" width="500px"}

public bool AddImageToDB(byte[] imageData, int id)
{
try
{
using (SqlConnection connection = new SqlConnection("ConnectionString"))
{
if (connection.State != System.Data.ConnectionState.Open)
{
connection.Open();
}
using (SqlCommand cmd = connection.CreateCommand())
{
cmd.CommandText = "spAddImages";
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@ID", id).SqlDbType = System.Data.SqlDbType.Int;
cmd.Parameters.AddWithValue("@ImageData", (object)imageData).SqlDbType = System.Data.SqlDbType.Image;
int m = cmd.ExecuteNonQuery();
if (m > 0)
{
return true;
}
else
{
return false;
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}


{/codecitation}

once the code section is finished, we are using in Stored procedure to save the image to database.



Stored Procedure Script


{codecitation class="brush:sql; gutter: true;" width="500px"}

GO
/****** Object: StoredProcedure [dbo].[spAddImages] Script Date: 06/19/2009 22:19:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: RRaveen
-- Create date: 2009.06.18
-- Description: add image to database
-- =============================================
ALTER PROCEDURE [spAddImages]
-- Add the parameters for the stored procedure here
@ImageData image,
@ID int

AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

-- Insert statements for procedure here
INSERT INTO dbo.UserImages
([ID]
,[ImageData])
VALUES
(@ID
,@ImageData)
END

{/codecitation}

That's all i hope this will help to you work around save image to Sql Server database.

Use Code

First design page like this way or own your way, then copy first method code and paste in your class or project.That's change file upload control name or id according your control name.

Conclusion

This article explained about save to image to Sql Server database using C# in ASP.NET.and to pick up file from the client using file upload control.

Thank you

RRaveen

 
Sign Up to vote for this article
 
About Author
 
RRaveen
Occupation-Software Engineer
Company-TGS
Member Type-Gold
Location-Singapore
Joined date-03 Jun 2009
Home Page-codegain.com
Blog Page-www.codegain.com
- B.Sc. degree in Computer Science. - 4+ years experience in Visual C#.net and VB.net - Obsessed in OOP style design and programming. - Designing and developing Network security tools. - Designing and developing a client/server application for sharing files among users in a way other than FTP protocol. - Designing and implementing GSM gateway applications and bulk messaging. - Windows Mobile and Symbian Programming - Having knowledge with ERP solutions
 
 
Other popularSectionarticles
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top