Saturday 4 August 2012

Insert Images to SqlServer in ASP .NET


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";       
 } 

No comments:

Post a Comment

Popular posts