Save images in SQL Server database using C# in ASP.NET

1 Create an Table in Sql Server Database.
 

CREATE TABLE [dbo].[Images](

[ImageName] [varchar]

(50),

[Image] [image] NULL

)

2. Write a code to save select image into DataBase table.

if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != "")

{

byte[] imageSize = new byte[FileUpload1.PostedFile.ContentLength];

HttpPostedFile uploadedImage = FileUpload1.PostedFile;

uploadedImage.InputStream.Read(imageSize, 0, (

int)FileUpload1.PostedFile.ContentLength);

// Create SQL Connection

SqlConnection sqlConn = new SqlConnection("Data Source=Server Name;Initial Catalog=DatabaseName;Integrated Security=True");

// Create SQL Command

SqlCommand cmd = new SqlCommand();

cmd.CommandText =

"INSERT INTO Images(ImageName,Image)" +

" VALUES (@ImageName,@Image)";

cmd.CommandType = CommandType.Text;

cmd.Connection = sqlConn;

SqlParameter ImageName = new SqlParameter("@ImageName", SqlDbType.VarChar, 50);

ImageName.Value = FileUpload1.FileName;

cmd.Parameters.Add(ImageName);

SqlParameter UploadedImage = new SqlParameter("@Image", SqlDbType.Image, imageSize.Length);

UploadedImage.Value = imageSize;

cmd.Parameters.Add(UploadedImage);

sqlConn.Open();

int result = cmd.ExecuteNonQuery();

sqlConn.Close();

if (result > 0) lblMessage.Text = "File Uploaded and Saved";

}

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s