Wednesday, January 23, 2019

Upload Image in asp.net c# and save image path to sql server database

In this article i have explain how to upload image to folder using asp.net c# and save into sql database.

Step 1 : Create database table into sql server 

create table tblImageDetails(
                                            id int identity(1,1) primary key,
                                            image_Name nvarchar(200),
                                           uploaded_Path nvarchar(200)
)

Step 2 : Add connection string and folder path to web.config file in your project.

  <appSettings>
      <add key="ConnectionString1" value="Data Source=LAPTOP-ISNBQ76D;Initial Catalog=test;Integrated Security=True"/>
     <add key="FolderPath" value="uploads"/>
  </appSettings>

Step 3 : Create a new web form and add the following code to your web form. Here  web page is upload-image.aspx.

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Uplaod Images </title>
    <style>
        table{
                width: 100%;
                text-align: center;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:Label ID="lblWarning" runat="server" style="font-size:1.2rem;color:red;"></asp:Label>
            <asp:Panel ID="pnlData" runat="server" style="border: 1px solid #ddd;margin-bottom: 1rem;margin-top: 1rem;width:60%"></asp:Panel>
            <asp:FileUpload ID="imageFile" runat="server" />
            <asp:Button ID="btnUpload" runat="server" Text="Upload " OnClick="btnUpload_Click" />
        </div>
    </form>
</body>
</html>

Step 4 : Now add the following c# code into your cs file like upload-image.aspx.cs

using System;
using System.Configuration;
using System.IO;
using System.Web.UI;
using System.Data.SqlClient;

namespace demo
{
    public partial class upload_image : System.Web.UI.Page
    {
        SqlConnection conn = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString1"]);
        protected void Page_Load(object sender, EventArgs e)
        {
            //Call displayImageData() function when page is not is post back
            if (!IsPostBack)
            {
                displayImageData();
            }
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            if (imageFile.HasFile)
            {
                //Get the name of image
                string FileName = imageFile.PostedFile.FileName;

                //Get the Extension of image
                string Extension = Path.GetExtension(imageFile.PostedFile.FileName);

                //Get The folder path from web.config file 
                string FolderPath = ConfigurationManager.AppSettings["FolderPath"];
                FolderPath +="/"+ System.DateTime.Now.Second + FileName;
                //Get the server path

                string FilePath = Server.MapPath(FolderPath);
                //Save image to uploader
                imageFile.SaveAs(FilePath);

                if (insertImageToDatabase(FileName, FolderPath))
                {
                    lblWarning.Text = "Image Successfully Upload and save into database !";
                    displayImageData();
                }
                else
                {
                    lblWarning.Text = "Error Occur !";
                }
            }
            else
            {
                lblWarning.Text = "Please Choose image before click !";
            }
        }

        //Insert image data to database
        protected bool insertImageToDatabase(string imageName, string imagePath)
        {
            try
            {
                conn.Open();
                string sql = "insert into tblImageDetails(" +
                                "image_Name," +
                                "uploaded_Path" +
                                ") values(" +
                                "@image_Name," +
                                "@uploaded_Path" +
                                ")";
                SqlCommand cmd = new SqlCommand(sql, conn);
                cmd.Parameters.AddWithValue("@image_Name", imageName);
                cmd.Parameters.AddWithValue("@uploaded_Path", imagePath);
                int i = cmd.ExecuteNonQuery();
                if(i>0)
                {
                    return true;
                }
            }
            catch(Exception ex)
            {
             
            }
            finally
            {
                conn.Close();
            }
            return false;
        }

        //Get details of image data and set to panel control for display data
        protected void displayImageData()
        {
            try
            {
                conn.Open();
                string sql = "select * from tblImageDetails";
                SqlCommand cmd = new SqlCommand(sql,conn);
                SqlDataReader sRd = cmd.ExecuteReader();
                int c = 1;
                if (sRd.HasRows)
                {
                    pnlData.Controls.Add(new LiteralControl("<table><tr>"));
                    pnlData.Controls.Add(new LiteralControl("<th>Sr. No </th>"));
                    pnlData.Controls.Add(new LiteralControl("<th>Image Name</th>"));
                    pnlData.Controls.Add(new LiteralControl("<th>Image </th>"));
                    pnlData.Controls.Add(new LiteralControl("</tr>"));
                    while(sRd.Read())
                    {
                        pnlData.Controls.Add(new LiteralControl("<tr>"));
                        pnlData.Controls.Add(new LiteralControl("<td>" + (c++) + "</td>"));
                        pnlData.Controls.Add(new LiteralControl("<td>"+sRd["image_Name"]+"</td>"));
                        pnlData.Controls.Add(new LiteralControl("<td><img src='"+ sRd["uploaded_Path"] + "' height='50' width='50' title='" + sRd["image_Name"] + "' ></td>"));
                        pnlData.Controls.Add(new LiteralControl("</tr>"));
                    }
                    pnlData.Controls.Add(new LiteralControl("</table>"));
                }
            } catch(Exception ex)
            {

            } finally
            {
                conn.Close();
            }
        }

    }
}

Output :

Featured Post

What is JavaScript? What is the role of JavaScript engine?

  The JavaScript is a Programming language that is used for converting static web pages to interactive and dynamic web pages. A JavaScript e...