Database Structure
Fileupload.aspx
- <asp:FileUpload ID=”FileUpload” runat=”server” />
-
- <asp:Button ID=”btnsubmit” runat=”server” Text=”Upload” OnClick=”btnsubmit_Click” />
-
- <asp:Label ID=”alert” runat=”server”></asp:Label>
-
- <asp:gridview ID=”Fileup” runat=”server” />
Fileupload.aspx.cs
Storing a image into database:
CODE:
- protected void btnsubmit_Click(object sender, EventArgs e)
- {
- try
- {
- byte[] imgbyte = null;
- if(FileUpload.HasFile & FileUpload.PostedFile != null)
- {
- HttpPostedFile file = FileUpload.PostedFile;
- imgbyte = new byte[file.ContentLength];
- file.InputStream.Read(imgbyte, 0, file.ContentLength);
- }
- SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[“userconnstring”].ConnectionString);
- SqlCommand cmd = new SqlCommand(“insert into tbl_Imgdb ([Image_Name],[Image_Detail]) values (@Image_Name,@Image_Detail)”, con);
- con.Open();
- cmd.Parameters.AddWithValue(“@Image_Name”, FileUpload.PostedFile.FileName);
- cmd.Parameters.AddWithValue(“@Image_Detail”, imgbyte);
- cmd.ExecuteNonQuery();
- alert.Text = “Image Uploaded Successfully”;
- con.Close();
- }
- catch(Exception ex)
- {
- throw ex;
- }
- }
Binding a image ina gridview display
Add this code in a gridview column (to convert the image. display into gridview)
- <asp:TemplateField>
- <HeaderTemplate>Image_Detail</HeaderTemplate>
- <ItemTemplate>
- <img src=’data:Image_Detail/jpg;base64, <%# Eval(“Image_Detail”) != System.DBNull.Value ? Convert.ToBase64String((byte[])Eval(“Image_Detail”)) : string.Empty %>’ alt=”image” height=”75px” width=”100px”/>
- </ItemTemplate>
- </asp:TemplateField>
Output:
Screen 1:
Screen 2:[Uploading Image]