Gautam Buddha Temple Varanasi,Varanasi - Buddhist Pilgrimage

Saturday, September 4, 2010

Insert Images to SqlServer in ASP .NET

Here I am explaining how insert images into database using asp.net.

 protected void Button1_Click(object sender, EventArgs e)  
{
FileUpload fileUpload1 = ((FileUpload)(this.FindControl("fileUpload1")));
if (((fileUpload1.PostedFile == null) || (string.IsNullOrEmpty(fileUpload1.PostedFile.FileName) || (fileUpload1.PostedFile.InputStream == null))))
{
Label1.Text = "Please Upload Valid picture file";
return;
}
int len = fileUpload1.PostedFile.ContentLength;
byte[] pic = new byte[len];
fileUpload1.PostedFile.InputStream.Read(pic, 0, len);
string extension = System.IO.Path.GetExtension(fileUpload1.PostedFile.FileName).ToLower();
string MIMEType = null;
switch (extension)
{
case ".gif":
MIMEType = "image/gif";
break;
case ".jpg":
case ".jpeg":
case ".jpe":
MIMEType = "image/jpeg";
break;
case ".png":
MIMEType = "image/png";
break;
default:
Label1.Text = "Not a Valid file format";
return;
break;
}
string fname = txtName.Text;
string lname = txtLName.Text;
string gender = rdGender.SelectedItem.Text;
string age = drpAge.SelectedItem.Text;
string state = txtState.Text;
SqlConnection myConnection;
myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["StrConnectSan"].ToString());
SqlCommand myCommand = new SqlCommand("usp_InsertPersonDetail", myConnection);
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.Add("@FirstName", SqlDbType.VarChar, 50).Value = fname;
myCommand.Parameters.Add("@LastName", SqlDbType.VarChar, 50).Value = lname;
myCommand.Parameters.Add("@GenderID", SqlDbType.VarChar, 50).Value = gender;
myCommand.Parameters.Add("@Age", SqlDbType.VarChar, 50).Value = age;
myCommand.Parameters.Add("@MCA", SqlDbType.VarChar, 50).Value = str;
myCommand.Parameters.Add("@State", SqlDbType.VarChar, 50).Value = state;
myCommand.Parameters.Add("@MIMEType", SqlDbType.VarChar, 50).Value = MIMEType;
myCommand.Parameters.Add("@ImageData",SqlDbType.Image,16).Value = pic;
myCommand.Parameters.Add("@Length", SqlDbType.VarChar, 50).Value = len;
myConnection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close();
msg.Text = "Record save successfully";
}


Thanks & Regards
Santosh

2 comments:

  1. Hi,
    Your article are really awesome.actually i was in search for some good articles on http://www.mindstick.com/Blog/184/Save%20image%20in%20SqlServer%20using%20C and finally i got one.
    The most important is the simplicity which will be very helpful for the beginners. Check out this link...

    http://www.mindstick.com/Blog/184/Save%20image%20in%20SqlServer%20using%20C

    It is also helped me to complete my task.
    Thanks

    ReplyDelete
  2. Thankyou so much sharing for informative valuable post. Many people will profit from this post in their business Great Job, Keep it up.
    Comex signals

    Silver tips

    ReplyDelete