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 |