WorldofASP.NET : ASP.NET Directory, Tutorial, Hosting, and Source Code
You are 1 of 146 users


WorldofASP.NET >> Csharp Programming >> Unedited Csharp

Upload and retrieve image to and from database

using FileUpload control to store image in SQL Server
Published Date : 02 Jun 2008
Author : Hans Candra
Language : C#
Platform : .NET
Technology : Visual Studio,ASP.NET,Web Forms,SQL
Views : 6513
Rating : (0 votes so far)



Introduction

One of the popular questions of databases and the web is: "How can I upload an image into a database?” ASP.NET provides a simple mechanism to upload image files to a database, like SQL Server. The images can be stored in a database table attribute that is of image data-type.

Main

SQL Stored Procedure to save image to database

ALTER proc [dbo].[usp_SetUserPhoto]
@Image image,
@userid int
as

update tblUser set UserPhoto = @Image 
where userid = @userid

User Photo Web Form

Creating UserPhoto.aspx Web Form to upload image. This web from can upload up to three different user photo and validate the size, data type, and resolution before insert it to the database. It must below 500kb, a jpg or gif image type, and in 350 x 350 resolution.



protected void btnUploadImage_Click(object sender, EventArgs e)
    {
        Button oButton = (Button)sender;
        string sImageType = oButton.ID;

        HttpPostedFile sImageFile = null;

        switch (sImageType)
        {
            case "UserPhoto":
                sImageFile = Request.Files[0];
                break;

            case "UserPhoto2":
                sImageFile = Request.Files[1];
                break;

            case "UserPhoto3":
                sImageFile = Request.Files[2];
                break;
            default:
                break;
        }

        if (sImageFile != null && sImageFile.FileName.Length > 0)
        {
            int iImageLength = sImageFile.ContentLength;
            byte[] bImageData = null;
            FileInfo fInfo = new FileInfo(sImageFile.FileName);
            long numBytes = fInfo.Length;
            string sExtension = fInfo.Extension.ToLower();

            if (numBytes > 500000)
            {
                lblMsg.Text = "The image file size cannot be greater than 500 KB.";
            }
            else if (sExtension == ".jpg" || sExtension == ".gif")
            {
                if (Cookie.UserID != 0)
                {
                    byte[] bdata = new byte[sImageFile.ContentLength];
                    sImageFile.InputStream.Read(bdata, 0, bdata.Length);
                    System.Drawing.Image iImage = 
System.Drawing.Image.FromStream(new MemoryStream(bdata));
                    if (iImage.Width > 350 || iImage.Height > 350)
                    {
                        lblMsg.Text = "The image width or height 
cannot be greater than 350 pixels";
                    }
                    else
                    {
                        FileStream fStream = new FileStream
(sImageFile.FileName, FileMode.Open, FileAccess.Read);
                        BinaryReader br = new BinaryReader(fStream);
                        bImageData = br.ReadBytes((int)numBytes);
                        switch (sImageType)
                        {
                            case "UserPhoto":
                                User.UserPhoto = bImageData;
                                break;

                            case " UserPhoto2":
                                User. UserPhoto2 = bImageData;
                                break;

                            case " UserPhoto3":
                                User.UserPhoto3 = bImageData;
                                break;
                            default:
                                break;
                        }
                    }
                }
            }
            else
            {
                lblMsg.Text = "Please upload the file with file extension 
in jpeg or gif.";
            }
        }
        else
        {
            lblMsg.Text = "Please upload your image file.";
        }
    }




User Data Access Layer Class to Connect to database
public class User
{
private byte[] bUserPhoto;
public byte[] UserPhoto
        {
            get
            {
                SqlConnection conn = new SqlConnection
(Connection.GetMasterConnString());
                conn.Open();
                SqlCommand cmd = conn.CreateCommand();
                cmd.CommandText = "usp_GetUserPhoto";
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add("@userid", SqlDbType.VarChar, 0).Value 
= iClientID.ToString();
                cmd.Parameters.Add("@Image", SqlDbType.Image, 0).Value 
= value;
while (dr.Read())
            {
try
                {
                    bUserLogo = (byte[])dr["UserPhoto"];
                }
                catch (Exception ex)
                {
                    bCompanyLogo = null;
                }
            }
Con.Close();
}

            set
            {
                SqlConnection conn = new SqlConnection
(Connection.GetMasterConnString());
                conn.Open();
                SqlCommand cmd = conn.CreateCommand();
                cmd.CommandText = "usp_SetUserPhoto";
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add("@userid", SqlDbType.VarChar, 0).Value = iClientID.ToString();
                cmd.Parameters.Add("@Image", SqlDbType.Image, 0).Value = value;
                cmd.ExecuteNonQuery();
                conn.Close();
            }
        }

}


Retrieve Image From Database



Displaying image form
<%@ WEBHANDLER LANGUAGE="C#" CLASS="DisplayImage" %>

using System;
using System.Web;
using FreeLiveChat.Library;
using System.IO;
public class DisplayImage : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        if (context.Request.QueryString["ClientID"] != null)
        {
            if (context.Request.QueryString["Type"] != null)
            {
                byte[] bImageData = null;
                System.Drawing.Image NewImage = null;
                System.Drawing.Image ThumbnailImage = null;
                byte[] ThumbnailByte = null;
                MemoryStream ms = null;
                switch (context.Request.QueryString["Type"])
                {
                    case "UserPhoto":

                        bImageData = User.UserPhoto;
                        ms = new MemoryStream(bImageData, 0, bImageData.Length);
                        break;
                    case " UserPhoto2":
                        bImageData = User.UserPhoto2;
                        ms = new MemoryStream(bImageData, 0, bImageData.Length);
                        break;
                    case " UserPhoto3":
                        bImageData = User.UserPhoto3;
                        ms = new MemoryStream(bImageData, 0, bImageData.Length);
                        break;
                    default:
                        break;
                }
                NewImage = System.Drawing.Image.FromStream
(new MemoryStream(bImageData));
                ThumbnailImage = NewImage.GetThumbnailImage
(NewImage.Width, NewImage.Height, null, new System.IntPtr());
                ThumbnailImage.Save(ms, NewImage.RawFormat);
                ThumbnailByte = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(ThumbnailByte, 0, Convert.ToInt32(ms.Length));
                context.Response.ContentType = "image/gif";
                context.Response.BinaryWrite(ThumbnailByte);
            }
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}

Conclusion

The main emphasis in this article was on uploading images to a SQL Server database and then displaying those images in a webform using asp label control. There are a lot of different articles explaining the technique for uploading to the database if you want to learn more.

References

Include all the useful links or references that can help users learn about your tutorial

  1. Upload and read image in ASP.NET
  2. Images in SQL Server




            Other Related and Popular Articles :

            Handling Cookie in ASP.NET
            Create a class to insert and retrieve cookie

            Launch Internet Explorer from Windows Application
            Exposing SHDocVw class to open IE

            Value Type and Reference Type in C
            It will give a clear idea about value type and reference type in c#. Thus help to readers to use proper data type in coding in their application.

            Convert and Bind Data to a Vertical DataGrid
            How to convert a DataBase Table to a Vertical View and Bind it to a DataGrid

            CaptchaImage
            CaptchaImage


            Author Profile : Hans Candra

            Click here to view Author Profile


            How would you rate the quality of this content?
            Poor Excellent

            Comments

            Leave New Comments


            Article Content copyright by Hans Candra
            Everything else Copyright © by WorldofASP.NET 2009

            Category
            .NET 3.5
            AJAX and ATLAS
            ASP.NET
            C# Programming
            Classic ASP
            Enterprise Systems
            General .NET
            VB.NET Programming
            Announcements
            Earn Cash by writing an article or review
            For more info Click here







            Legend : - Within 3 Days - Within 6 Days - Within 9 Days

            Home | Add Resources | Sponsored Listings | Advertise with Us | SiteMap 1 | SiteMap 2 | Link To Us | Contact Us
            © 2002-2009 Worldofasp.net ASP.NET Directory, Hosting and Tutorials | All rights reserved
            Our Partners : ASP.NET Web Hosting | Windows Web Hosting | ASP.NET Hosting | Phone Card | PHP Directory | Bangkok Hotels |Calling Card |Stock Investing