How to Insert images into SQL Server from ASP.NET Using C#
Introduction
Here I will explain how to insert images into database into binary form using asp.net Description
First we create image table in our database.
After that add System.Configuration namespace in code behind because in this namespace contains classes representing connection information with sql. We already explain, how to create connection string in our web site. For details click here!
After that add following code in code behind
string strcon = ConfigurationManager.ConnectionStrings ["ConnectionString"].ConnectionString; protected void Page_Load(object sender, EventArgs e) { } /// <summary> /// btnUpload_Click event is used to upload images into database /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnUpload_Click(object sender, EventArgs e) { //Condition to check if the file uploaded or not if (fileuploadImage.HasFile) { //getting length of uploaded file int length = fileuploadImage.PostedFile.ContentLength; //create a byte array to store the binary image data byte[] ImgByte = new byte[length]; //store the currently selected file in memeory HttpPostedFile img = fileuploadImage.PostedFile; //set the binary data img.InputStream.Read(ImgByte, 0, length); string ImageName = txtImageName.Text; //use the web.config to store the connection string SqlConnection connection = new SqlConnection(strcon); connection.Open(); SqlCommand cmd = new SqlCommand("INSERT INTO Image (ImageName,Image) VALUES (@ImageName,@Image)", connection); cmd.Parameters.Add("@ImageName", SqlDbType.VarChar, 50).Value = ImageName; cmd.Parameters.Add("@Image", SqlDbType.Image).Value = ImgByte; int count = cmd.ExecuteNonQuery(); connection.Close(); if (count == 1) { txtImageName.Text = string.Empty; ScriptManager.RegisterStartupScript(this, this.GetType(), "alertmessage", "javascript:alert('" + ImageName + " image inserted successfully')", true); } } }
At Last, we have compile our aspx page on local host and insert image . After inserting our table structure like this
We hope this will help you......If you enjoyed this post, please like this blog!
Thanks for this article. Really helpful for me..
ReplyDeleteWaiting for more post..
lovely post :) keep it up
ReplyDelete