Sunday 9 June 2013

How to upload image in Sql Server and show this image in Datalist control in asp.net


How to upload image in Sql Server  and show this image  in Datalist control  in asp.net ( apply condition you  upload only 10.6 kb less than image  and  with  png ,jpg ,jpeg format


//execute these line  in Sql Server …………………………………..

create database SocialNet
use SocialNet

create table ImageGallery (SrNo int identity(1,1) primary key,EmailId nvarchar(50),UImage nvarchar(max),UDatetime datetime)

####################################################

<%@ Page Title="Image Galary" Language="C#" MasterPageFile="~/User.master" AutoEventWireup="true" CodeFile="AddImageForGallery.aspx.cs" Inherits="ImageGalary" %>

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder2" Runat="Server">
    <style type="text/css">
        .style1
        {
            height: 26px;
        }
        .style2
        {
            height: 122px;
        }
    </style>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <table width="100%" >
<tr><td colspan="2">
<center>
    <asp:Label ID="Label1" runat="server" Text="Add Image  from your Computer"
        Font-Bold="True" Font-Italic="True" ForeColor="Red"></asp:Label>
    </center>
    </td></tr>
<tr><td>
    <asp:Label ID="Label2" runat="server" Text="Upload  Image  "></asp:Label>
    </td><td>
        <asp:FileUpload ID="FileUpload1" runat="server" />
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
            ControlToValidate="FileUpload1" ErrorMessage="Please upload Image"
            ForeColor="Red" SetFocusOnError="True" ValidationGroup="g1">*</asp:RequiredFieldValidator>
    </td></tr>
<tr><td class="style1"></td><td class="style1">
    <asp:Button ID="BtnUpload" runat="server" Text="Upload"
        onclick="BtnUpload_Click" ValidationGroup="g1" />
    </td></tr>
<tr><td class="style1"></td><td class="style1">
    <asp:Label ID="Lmessage" runat="server" ForeColor="Red" Visible="False"></asp:Label>
    </td></tr>
<tr><td colspan="2" class="style2">
    <asp:DataList ID="DataList1" runat="server" RepeatColumns="4"
        DataKeyField="srno" onitemcommand="DataList1_ItemCommand" 
         >
        <ItemTemplate>
            <asp:Image ID="Image2" runat="server" Height="73px"
                ImageUrl='<%# Eval("UImage","Image_Gallery/{0}") %>'  Width="133px" />
            <asp:LinkButton ID="LDelete" runat="server" CommandName="del"
                >Delete</asp:LinkButton>
            <asp:Label ID="Label3" runat="server" Text='<%# Eval("srno") %>'
                Visible="False"></asp:Label>
        </ItemTemplate>
    </asp:DataList>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server"></asp:SqlDataSource>
    </td></tr>
</table>
</asp:Content>

###################################################

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

public partial class ImageGalary : System.Web.UI.Page
{

    SqlConnection con;
    SqlCommand cmd;
   
protected void Page_Load(object sender, EventArgs e)
    {
    con = new SqlConnection("Data Source=KUSH-PC\\KUSH;Initial Catalog=SocialNet;Integrated Security=True");
        if (!IsPostBack)
        {
            BindDataList();
        }

    }

   //   code  for how to bind datalist………………………………….
 private void BindDataList()
    {
        try
        {
            con.Open();
            SqlCommand cmd = new SqlCommand("select SrNo,UImage,UDatetime from ImageGallery where EmailId='" + Session["email"].ToString() + "'", con);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);
            DataList1.DataSource = ds;
            DataList1.DataBind();
            con.Close();
        }
        catch(Exception ex)
        {

            Lmessage.Visible = true;
            Lmessage.Text=ex.Message;

        }
    }
    protected void BtnUpload_Click(object sender, EventArgs e)
    {
        try
        {
//  code  for  only  upload png,jpg,jpeg format  for  image………………
string exe = Path.GetExtension(FileUpload1.FileName).ToLower();
            string filename = FileUpload1.FileName;
            if (exe == ".png" || exe == ".jpg" || exe == ".jpeg")
            {
//  code  for  upload  image less than 10.6 kb only……………… 1 kb=1024 bytes  -> 10.6 kb= 10854.4 bytes
                if (FileUpload1.FileBytes.Length <= 10855)
                {
                 //  code for  generate unique  name with extension

                    filename = Guid.NewGuid().ToString() + Path.GetExtension(filename);
                    con.Open();
                    cmd = new SqlCommand("insert into ImageGallery(EmailId,UImage,UDatetime) values (@EmailId,@UImage,@UDatetime)", con);
                    cmd.Parameters.AddWithValue("@EmailId", Session["email"].ToString());
                    cmd.Parameters.AddWithValue("@UImage", filename);
                    cmd.Parameters.AddWithValue("@UDatetime", DateTime.Now);

                    FileUpload1.SaveAs(Server.MapPath("~/Image_Gallery/") +filename);
                    cmd.ExecuteNonQuery();

                    con.Close();
                }
                else
                {
                    Lmessage.Visible = true;
                    Lmessage.Text = "Please upload image less than 10.6 kb  ";
                }
                BindDataList();
            }
            else
            {
                Lmessage.Visible = true;
                Lmessage.Text = "Please select png,jpg,jpeg file for image upload";

            }
        }

        catch(Exception ex)
        {

            Lmessage.Visible = true;
            Lmessage.Text=ex.Message;

        }
    }

//  code  for  delete image by serialno ……….

    protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
    {
       Image img = (Image)e.Item.FindControl("Image2");
      
        if (e.CommandName == "del")
        {

            DirectoryInfo dd = new DirectoryInfo(Server.MapPath("Image_Gallery"));
            foreach (FileInfo ff in dd.GetFiles())
            {
                if (ff.Name == Path.GetFileName(img.ImageUrl))
                    ff.Delete();
            }
            Label l = (Label)e.Item.FindControl("Label3");
                con = new SqlConnection("Data Source=KUSH-PC\\KUSH;Initial Catalog=SocialNet;Integrated Security=True");
            SqlCommand cmd = new SqlCommand("delete from ImageGallery where srno="+Convert .ToInt32 (l.Text ), con);
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
       
        }
        BindDataList();
    }
 }

0 comments:

Post a Comment