Thursday, April 7, 2011

Save and Retrieve Images from the Database using ASP.NET 2.0 and ASP.NET 3.5



CREATE TABLE EmpDetails
(
empid int IDENTITY NOT NULL,
empname varchar(20),
empimg image
)





using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data;
using System.Data.SqlClient;
public partial class Default5 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        SqlConnection connection = null;
        string FileType = string.Empty;
        try
        {
            FileUpload img = (FileUpload)imgUpload;
            System.Byte[] imgByte = null;
            if (img.HasFile && img.PostedFile != null)
            {
                //To create a PostedFile
                HttpPostedFile File = imgUpload.PostedFile;
                FileType = File.ContentType;

                //Create byte Array with file len
                imgByte = new Byte[File.ContentLength];
                //force the control to load data in array
                File.InputStream.Read(imgByte, 0, File.ContentLength);
            }
            // Insert the employee name and image into db
            string conn = ConfigurationManager.ConnectionStrings["EmployeeConnString"].ConnectionString;
            connection = new SqlConnection(conn);

            connection.Open();
            string sql = "INSERT INTO EmpDetails(empname,empimg) VALUES(@enm, @eimg) SELECT @@IDENTITY";
            SqlCommand cmd = new SqlCommand(sql, connection);
            cmd.Parameters.AddWithValue("@enm", FileType.ToString());
            cmd.Parameters.AddWithValue("@eimg", imgByte);
            int id = Convert.ToInt32(cmd.ExecuteScalar());
            lblResult.Text = String.Format("Employee ID is {0}", id);
        }
        catch (Exception ex)
        {
            lblResult.Text = "There was an error";
        }
        finally
        {
            connection.Close();
        }



    }
    protected void btnImage_OnClick(object sender, EventArgs e)
    {

        SqlConnection connection = null;
        string conn = ConfigurationManager.ConnectionStrings["EmployeeConnString"].ConnectionString;
        connection = new SqlConnection(conn);

        connection.Open();
        SqlCommand command1 = new SqlCommand("Select empimg  from EmpDetails where empid=2", connection);


        byte[] img = (byte[])command1.ExecuteScalar();
        System.IO.MemoryStream str = new System.IO.MemoryStream();
        str.Write(img, 0, img.Length);
        System.Drawing.Bitmap bit = new System.Drawing.Bitmap(str);
        Response.ContentType = "image/GIF";//or you can select your imagetype from database or directly write it here
        bit.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);

        connection.Close();
        //Image1.ImageUrl = "~/ShowImage.ashx?id=" + img;
    }

    protected void btnImageMul_OnClick(object sender, EventArgs e)
    {
        SqlConnection connection = null;
        string conn = ConfigurationManager.ConnectionStrings["EmployeeConnString"].ConnectionString;
        connection = new SqlConnection(conn);

        connection.Open();
        SqlCommand command1 = new SqlCommand("Select empid,empname,empimg  from EmpDetails  ", connection);
        byte[] img = null;
        DataTable dt = new DataTable();
        SqlDataAdapter da = new SqlDataAdapter();
        command1.CommandType = CommandType.Text;
        da.SelectCommand = command1;
        da.Fill(dt);
        dt.Columns.Add("imgFile");


        for (int K = 0; K < dt.Rows.Count; K++)
        {
            System.IO.MemoryStream str = new System.IO.MemoryStream();
            img = (byte[])dt.Rows[K]["empimg"];
            str.Write(img, 0, img.Length);


            System.Drawing.Bitmap bit = new System.Drawing.Bitmap(str);
            Response.ContentType = dt.Rows[K]["empname"].ToString();   //"image/GIF";//or you can select your imagetype from database or directly write it here
            bit.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);
            //   dt.Rows[K]["imgFile"] = "~/ShowImage.ashx?id=" + img;
            dt.Rows[K]["imgFile"] = img;
            //Image1.ImageUrl = "~/ShowImage.ashx?id=" + img;
        }
        dt.AcceptChanges();


        grdView.DataSource = dt;
        grdView.DataBind();
        connection.Close();
    }





}
<table cellpadding="0" cellspacing="0" width="100%">
        <tr>
            <td>
                <asp:Label ID="lblEmpName" runat="server" Text="Employee Name"></asp:Label>
                &nbsp;&nbsp;&nbsp;&nbsp;
                <asp:TextBox ID="txtEName" runat="server"></asp:TextBox>
                <br />
                <asp:Label ID="lblImage" runat="server" Text="Employee Image"></asp:Label>
                &nbsp;&nbsp;&nbsp;&nbsp;
                <asp:FileUpload ID="imgUpload" runat="server" />
                <br />
                <br />
                <asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit_Click" Text="Submit" />
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp
                <asp:Label ID="lblResult" runat="server" ForeColor="#0066FF"></asp:Label>
                <br />
                <hr />
                <asp:Image ID="Image1" Style="width: 200px" runat="server" />
                <asp:Button ID="btnImage" runat="server" Text="GET IMAGE" OnClick="btnImage_OnClick" />
                <asp:Button ID="btnImageMul" runat="server" Text="GET Multiple IMAGE" OnClick="btnImageMul_OnClick" />
            </td>
        </tr>
        <tr>
            <td>
                <asp:GridView ID="grdView" runat="server">
                </asp:GridView>
            </td>
        </tr>
    </table>

No comments:

Post a Comment