March 29, 2011

Upload Image using code using c sharp dot net

This is example of c#.net code to Upload Image through image upload control and save image to table of database.

using System.Data;
using System.Data.SqlClient;
public partial class ImageUpload : System.Web.UI.Page
{
    SqlConnection sqlcon=new SqlConnection(@"Server=SQLEXPRESS;database=abc;uid=xxxx;pwd=yyyy;");
    SqlCommand sqlcmd=new SqlCommand();
    String ImageName,ImageType;
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            int len = FileUpload1.PostedFile.ContentLength;
            byte[] picture = new byte[len];
            ImageName = FileUpload1.FileName;
            ImageType = FileUpload1.PostedFile.ContentType;
            sqlcon.Open();
            SqlCommand sqlcmd = new SqlCommand("insert into tesimage(ImgName,Img,ImgType) values (@Im, @Img, @ImgType)", sqlcon);
            sqlcmd.Parameters.Add("@Im", ImageName);
            sqlcmd.Parameters.Add("@Img", picture);
            sqlcmd.Parameters.Add("@ImgType", ImageType);
            sqlcmd.ExecuteNonQuery();
            sqlcon.Close();       
        }
   }
}

No comments:

Post a Comment