Pages

Monday, 15 October 2012

How to upload and show images from Database using ASP.NET in C#



How to upload and show images from Database using ASP.NET in C#


SQL Script for Table Creation


CREATE TABLE [dbo].[Emp_test](
      [Employee_ID] [int] IDENTITY(1,1) NOT NULL,
      [Employee_Image] [image] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
 


Steps:

1. Create a Web Page as below (Default.aspx):



<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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>Upload and Show Images</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="lblImage" runat="server" Text="Employee Image"></asp:Label>
&nbsp;&nbsp;&nbsp;&nbsp;
        <asp:FileUpload ID="imgUpload" runat="server" />
        <br />
        <asp:Label ID="Label1" runat="server" Text="Label" Font-Bold="True"
            ForeColor="Red" Visible="False"></asp:Label>
        <br />
        <asp:Button ID="btnUpload" runat="server" onclick="btnUpload_Click"
            Text="Upload Image" />
  
    &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" />
  
    </div>
    </form>
</body>
</html>



2. Add below code in Default.aspx.cs


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.Sql;
using System.Configuration;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        SqlConnection conn = null;
        Boolean size = CheckFileSize();
        if (size)
        {
            try
            {
                FileUpload imgfile = (FileUpload)imgUpload;
                Byte[] imgByte = null;
                if (imgfile.HasFile && imgfile.PostedFile != null)
                {
                    HttpPostedFile File = imgUpload.PostedFile;
                    //Create byte Array
                    imgByte = new Byte[File.ContentLength];
                    //forcefully load data in array
                    File.InputStream.Read(imgByte, 0, File.ContentLength);
                }
                string strconn = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
                conn = new SqlConnection(strconn);

                conn.Open();
                string sql = "INSERT INTO Emp_test(Employee_Image) VALUES(@empimg) SELECT @@IDENTITY";
                SqlCommand cmd = new SqlCommand(sql, conn);
                cmd.Parameters.AddWithValue("@empimg", imgByte);
                int id = Convert.ToInt32(cmd.ExecuteScalar());
                lblResult.Text = String.Format("Employee ID is {0}", id);
                // for showing image from database. Add this code after adding HTTP Handler
                Image1.ImageUrl = "~/ShowImageHandler.ashx?id=" + id;
            }
            catch
            {
                lblResult.Text = "There was an error";
            }
            finally
            {
                conn.Close();
            }
        }
        else
        {
            Label1.Visible = true;
            Label1.Text = "File size exceeds maximum limit 4 MB.";
        }
    }
    public Boolean CheckFileSize() //Method for checking file size
    {
        FileUpload imgfile = (FileUpload)imgUpload;
        if (imgfile.HasFile && imgfile.PostedFile.ContentLength < 4194300)
        {
            try
            {
                Label1.Text = "File name: " +
                imgfile.PostedFile.FileName + "<br>" +
                imgfile.PostedFile.ContentLength + " kb<br>" +
                "Content type: " +
                imgfile.PostedFile.ContentType;
            }
            catch (Exception ex)
            {
                Label1.Text = "ERROR: " + ex.Message.ToString();
            }
            return true;
        }
        else
        {
            return false;
        }
    }
}




In the above code one method named "CheckFileSize()" checks the file size before uploading to database. If the file size is more than 4 MB then code will show you message.

3. In order to show image on the page, we have to create an HTTP Handler. To add HTTP Handler, Right Click project > Add New Item > Generic Handler > ShowImageHandler.ashx.Add below code on ShowImageHandler.ashx

<%@ WebHandler Language="C#" Class="ShowImageHandler" %>


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

public class ShowImageHandler : IHttpHandler {
   
    public void ProcessRequest (HttpContext httpcontext)
    {
        Int32 empno;
        if (httpcontext.Request.QueryString["id"] != null)
            empno = Convert.ToInt32(httpcontext.Request.QueryString["id"]);
        else
            throw new ArgumentException("No parameter found");

        httpcontext.Response.ContentType = "image/jpeg";
        Stream strm = ShowImage(empno);
        byte[] buffer = new byte[4096];
        int byteSeq = strm.Read(buffer, 0, 4096);

        while (byteSeq > 0)
        {
            httpcontext.Response.OutputStream.Write(buffer, 0, byteSeq);
            byteSeq = strm.Read(buffer, 0, 4096);
        }       
    }
    public Stream ShowImage(int empno)
    {
        string strconn = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
        SqlConnection conn = new SqlConnection(strconn);
        string sql = "SELECT Employee_Image FROM emp_test WHERE Employee_ID = @ID";
        SqlCommand cmd = new SqlCommand(sql, conn);
        cmd.CommandType = CommandType.Text;
        cmd.Parameters.AddWithValue("@ID", empno);
        conn.Open();
        object img = cmd.ExecuteScalar();
        try
        {
            return new MemoryStream((byte[])img);
        }
        catch
        {
            return null;
        }
        finally
        {
            conn.Close();
        }
    }
    public bool IsReusable {
        get {
            return false;
        }
    }

}
 

The code shown above, uses the Request.QueryString[“id”] to retrieve the Employee_ID from it. The ID is then passed to the ‘ShowImage()’ method where the image is retrived from the database and stored in a MemoryStream object. 
After that We can read the stream into a byte array. By using OutputStream.Write(), we write the bytes to the stream and we get to see image.

4. After that you have to add below code on button click at the end of try block:

// for showing image from database. Add this code after adding HTTP Handler

                Image1.ImageUrl = "~/ShowImageHandler.ashx?id=" + id;

5. Please also change the connection information in Web.Config file before running.

6. Execute the code. You will see.

Browse the file you want to upload and click on "Upload Image" button.
If the file you have selected is below 4 MB size then you will see below screen.


If file size is above 4 MB then you will see below screen. Because File Upload control only accept 4 MB size files by default.


6. You can also increase or decrease upload file size by adding below code in Web.Config file in <system.web> ....</system.web> section.


<!-- <httpRuntime executionTimeout="MaxRuntime in Sec" maxRequestLength="file size in KB"/>-->

<httpRuntime executionTimeout="9999" maxRequestLength="6144"/>


I hope this post is useful and thanks for viewing it.
 Enjoy.........................................

No comments:

Post a Comment