How can I Store images in SQL database using Asp.net ?
Printable View
How can I Store images in SQL database using Asp.net ?
The following code shows how to use ADO.NET to store image field in SQL Server.
Code:public void StorePicture( string filename )
{
// Read the file into a byte array
using(FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read))
{
byte[] imageData = new Byte[fs.Length];
fs.Read( imageData, 0, (int)fs.Length );
}
using( SqlConnection conn = new SqlConnection(connectionString) )
{
SqlCommand cmd = new SqlCommand("StorePicture", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@filename", filename );
cmd.Parameters["@filename"].Direction = ParameterDirection.Input;
cmd.Parameters.Add("@blobdata", SqlDbType.Image);
cmd.Parameters["@blobdata"].Direction = ParameterDirection.Input;
// Store the byte array within the image field
cmd.Parameters["@blobdata"].Value = imageData;
conn.Open();
cmd.ExecuteNonQuery();
}
}
You can use this stored procedure to add image to sql database manually.
Code:CREATE PROCEDURE [sp_AddImage]
(
@img_pk INT OUTPUT ,
@img_data IMAGE
)
AS
INSERT INTO tbl_Image ( img_data)
VALUES ( @img_data )
IF @@ROWCOUNT=1
SET @img_pk=@@IDENTITY
GO