Uploading And Retrieving Images With SQL Database In ASP.NET Web Forms | ASP.NET

 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="INSERT_AND_RETRIEVING_IMAGES.WebForm1" %>


<!DOCTYPE html>


<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title></title>

    <style type="text/css">

        .auto-style1{

            width:100%;

        }

        .auto-style2 {

            width: 124px;

        }

    </style>

</head>

<body>

    <form id="form1" runat="server">

        <div>

            <table cellpadding="4" cellspacing="4" class="auto-style1">

                <tr>

                    <td class="auto-style2">IMAGE UPLOAD</td>

                    <td>

                        <asp:FileUpload ID="FileUpload1" runat="server"/>

                    </td>

                </tr>

                <tr>

                    <td class="auto-style2">&nbsp;</td>

                    <td>

                        <asp:Button ID="Button1" runat="server" Text="SAVE" Height="40px" Width="87px" OnClick="Button1_Click"/>

                        <asp:Label ID="Label1" runat="server" Text="Label" Visible="false"></asp:Label>

                    </td>

                </tr>

                <tr>

                    <td class="auto-style2">&nbsp;</td>

                    <td>&nbsp;</td>

                </tr>

                <tr>

                    <td class="auto-style2">&nbsp;</td>

                    <td>

                        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" ShowHeader="false">

                            <Columns>

                                <asp:TemplateField>

                                    <ItemTemplate>

                                        <table>

                                            <tr>

                                                <td>

                                                    <asp:Label ID="Label2" runat="server" Text='<%# Eval("Id") %>'></asp:Label>

                                                </td>

                                                <td>

                                                    <asp:Image ID="Image1" runat="server" Height="150" Width="150" ImageUrl='<%# Eval("Image_Name") %>'/>

                                                </td>

                                            </tr>

                                        </table>

                                    </ItemTemplate>

                                </asp:TemplateField>

                            </Columns>

                        </asp:GridView>

                    </td>

                </tr>

            </table>

        </div>

    </form>

</body>

</html>

Above File is INSERT_AND_RETRIEVING_IMAGES\WebForm1.aspx
















using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;

namespace INSERT_AND_RETRIEVING_IMAGES
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        string cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                fillGridView();
            }
            if (IsPostBack)
            {
                fillGridView();
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            try
            {
                using(SqlConnection con = new SqlConnection(cs))
                {
                    string path = Server.MapPath("images/");
                    if (FileUpload1.HasFile)
                    {
                        string fileName = Path.GetFileName(FileUpload1.FileName);
                        string extension = Path.GetExtension(fileName);
                        HttpPostedFile postedFile = FileUpload1.PostedFile;
                        int length = postedFile.ContentLength;

                        if (extension.ToLower() == ".jpg" || extension.ToLower() == ".png" || extension.ToLower() == ".jpeg")
                        {
                            if (length <= 1000000)
                            {
                                FileUpload1.SaveAs(path + fileName);
                                string name = "images/" + fileName;

                                string query = "INSERT INTO img VALUES(@img)";
                                SqlCommand cmd = new SqlCommand(query, con);
                                cmd.Parameters.AddWithValue("@img", name);
                                con.Open();
                                int a = cmd.ExecuteNonQuery();
                                if (a > 0)
                                {
                                    Label1.Text = "Inserted Successfully !!";
                                    Label1.ForeColor = System.Drawing.Color.Green;
                                    Label1.Visible = true;
                                    fillGridView();
                                }
                                else
                                {
                                    Label1.Text = "Insertion Failed !!";
                                    Label1.ForeColor = System.Drawing.Color.Red;
                                    Label1.Visible = true;
                                }
                                con.Close();
                            }
                            else
                            {
                                Label1.Text = "Image file should not be greater than 1 MB";
                                Label1.ForeColor = System.Drawing.Color.Red;
                                Label1.Visible = true;
                            }
                        }
                        else
                        {
                            Label1.Text = "Image format is not supported !!";
                            Label1.ForeColor = System.Drawing.Color.Red;
                            Label1.Visible = true;
                        }
                    }
                    else
                    {
                        Label1.Text = "Please Upload an Image !!";
                        Label1.ForeColor = System.Drawing.Color.Red;
                        Label1.Visible = true;
                    }
                }
            }
            catch (SqlException ex)
            {
                Response.Write("SqlException: " + ex.Message);
            }
            catch (Exception ex)
            {
                Response.Write("Exception: " + ex.Message);
            }
        }
        void fillGridView()
        {
            try
            {
                using(SqlConnection con = new SqlConnection(cs))
                {
                    con.Open();
                    string query = "SELECT * FROM img";
                    SqlDataAdapter sda = new SqlDataAdapter(query,con);
                    DataTable data = new DataTable();
                    sda.Fill(data);
                    GridView1.DataSource = data;
                    GridView1.DataBind();
                }
            }
            catch (SqlException ex)
            {
                Response.Write("SqlException: " + ex.Message);
            }
            catch (Exception ex)
            {
                Response.Write("Exception: " + ex.Message);
            }
        }
    }
}
Above File is INSERT_AND_RETRIEVING_IMAGES\WebForm1.aspx.cs



















<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  https://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.7.2" />
    <httpRuntime targetFramework="4.7.2" />
    <pages>
      <namespaces>
        <add namespace="System.Web.Optimization" />
      </namespaces>
      <controls>
        <add assembly="Microsoft.AspNet.Web.Optimization.WebForms" namespace="Microsoft.AspNet.Web.Optimization.WebForms" tagPrefix="webopt" />
      </controls>
    </pages>
  </system.web>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Antlr3.Runtime" publicKeyToken="eb42632606e9261f" />
        <bindingRedirect oldVersion="0.0.0.0-3.5.0.2" newVersion="3.5.0.2" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Web.Infrastructure" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" />
        <bindingRedirect oldVersion="0.0.0.0-13.0.0.0" newVersion="13.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
    </compilers>
  </system.codedom>
<connectionStrings>
<add name="dbcs" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=D:\DotNet\INSERT_AND_RETRIEVING_IMAGES\INSERT_AND_RETRIEVING_IMAGES\App_Data\Database1.mdf;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>
Above File is Web.config





Comments

Popular posts from this blog

Range Validator Control In ASP.NET Web forms | Form Validation | ASP.NET Web forms

Query String In ASP.NET Web Forms | State Management | ASP.NET | Web Forms

Validation Summary Control In ASP.NET Web forms | Form Validation | ASP.NET