Monday, July 9, 2012

Open File Dialog and Save image in Database

Aspx Page:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="sampleTest.WebForm2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Image ID="Image1" runat="server" Height="103px" ImageUrl="no_img.jpg" Width="127px" />
        <asp:LinkButton ID="chng_img" runat="server" OnClick="chng_img_Click">Change
    Image</asp:LinkButton>
        <asp:Panel ID="Panel1" runat="server" Visible="False" Width="274px">
            <asp:FileUpload ID="FileUpload1" runat="server" Width="256px" />
            <br />
            <asp:LinkButton ID="cancel_img" runat="server" OnClick="cancel_img_Click1">Cancel</asp:LinkButton>
            &nbsp;|
            <asp:LinkButton ID="update_img" runat="server" OnClick="update_img_Click">Update</asp:LinkButton>
        </asp:Panel>
    </div>
    </form>
</body>
</html>

Aspx.cs Page:

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.Data;
using System.Text;
using System.IO;

namespace sampleTest
{
    public partial class WebForm2 : System.Web.UI.Page
    {

        protected void chng_img_Click(object sender, EventArgs e)
        {
            Panel1.Visible = true;
        }

        protected void update_img_Click(object sender, EventArgs e)
        {
            Image1.ImageUrl = FileUpload1.PostedFile.FileName.ToString();

            SqlConnection cn = new SqlConnection(@"Data Source=Student-BCD1456;Initial Catalog=Victroy_Database;Persist Security Info=True;User ID=sa;Password=karthi");
            //SqlCommand cmd = new SqlCommand("update uprofile set simg = @img where sid = '" + Session["sid"].ToString() + "' ", cn);
            SqlCommand cmd = new SqlCommand("insert into tbl_img(img) values(@img);", cn);
            byte[] Img = new byte[FileUpload1.PostedFile.ContentLength];
            Stream str = FileUpload1.PostedFile.InputStream;
            str.Read(Img, 0, FileUpload1.PostedFile.ContentLength);
            cmd.Parameters.AddWithValue("img", Img);
            cn.Open();
            cmd.ExecuteNonQuery();
            cn.Close();

            Panel1.Visible = false;
        }

        protected void cancel_img_Click1(object sender, EventArgs e)
        { Panel1.Visible = false; }
    }
}

No comments:

Post a Comment