This example explains how to Save Images In Sqlserver Database In Asp.Net Using File Upload Control.
I am Uploading Images using FileUpload Control and saving or storing them in SQL Server database in ASP.NET with C# and VB.NET.
Database is having a table named Images with three columns.
1. ID Numeric Primary key with Identity Increment.
2. ImageName Varchar to store Name of picture.
3. Image column to store image in binary format.
After uploading and saving images in database, pics are displayed in GridView.
Write this code in Click Event of Upload Button
I am Uploading Images using FileUpload Control and saving or storing them in SQL Server database in ASP.NET with C# and VB.NET.
Database is having a table named Images with three columns.
1. ID Numeric Primary key with Identity Increment.
2. ImageName Varchar to store Name of picture.
3. Image column to store image in binary format.
After uploading and saving images in database, pics are displayed in GridView.
Html markup of the page look like
<form id="form1" runat="server"> <div> <asp:TextBox ID="txtName" runat="server" Width="95px"> </asp:TextBox> <asp:FileUpload ID="FileUpload1" runat="server"/> <asp:Label ID="lblMessage" runat="server">
</asp:Label> <asp:Button ID="btnUpload" runat="server" OnClick="btnUpload_Click" Text="Upload"/> </div> </form>
Write this code in Click Event of Upload Button
C# Code behind
protected void btnUpload_Click(object sender, EventArgs e){string strImageName = txtName.Text.ToString();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 con = new SqlConnection();con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;// Create SQL Command SqlCommand cmd = new SqlCommand();cmd.CommandText = "INSERT INTO Images(ImageName,Image)" +" VALUES (@ImageName,@Image)";cmd.CommandType = CommandType.Text;cmd.Connection = con; SqlParameter ImageName = new SqlParameter("@ImageName", SqlDbType.VarChar, 50);ImageName.Value = strImageName.ToString();cmd.Parameters.Add(ImageName); SqlParameter UploadedImage = new SqlParameter("@Image", SqlDbType.Image, imageSize.Length);UploadedImage.Value = imageSize;cmd.Parameters.Add(UploadedImage);con.Open();int result = cmd.ExecuteNonQuery();con.Close();if (result > 0)lblMessage.Text = "File Uploaded";GridView1.DataBind();}}
No comments:
Post a Comment