Click here to Skip to main content
15,867,453 members
Articles / Web Development / ASP.NET
Tip/Trick

Uploading an Image and Displaying It on the UI Page

Rate me:
Please Sign up or sign in to vote.
4.86/5 (7 votes)
17 Dec 2012CPOL 40.2K   11   3
Uploading an image and displaying it on the UI page

Introduction

In this example, I will explain how to get the full path of upload file from FileUpload control and Uploading the image and fetching the image from the data base using ASP.NET (C#), SQL Server 2008.

Background

In many forums, I saw the question like how to get the full path from file-upload control and uploading an image and fetching an image from database!

For all these questions, the answer is that we don't have change to get full path of upload file from file-upload control because of some security reasons but instead we can get the file name from the client machine.

The complete interface will look like:

Image 1

When you click on the browse button, a window will be opened in the client machine.

Image 2

Select a file, and click on the upload.

Image 3

UI Script

Click to enlarge image

Using the Code

C#
using System; 
using System.Web; 
using System.Web.UI;
using System.Data.SqlClient;
using System.Data; 
private static SqlConnection GetCon()
{
    return new SqlConnection("Data Source=.;Initial Catalog=uploadImage");
}
 
protected void Page_Load(object sender, EventArgs e)
{
    lblErrorMsg.Visible = false;
}
 
protected void ibtnUpload_Click(object sender, ImageClickEventArgs e)
{
    if (FileUpload1.HasFile)
    {
        if (IsImageFile((HttpPostedFile)FileUpload1.PostedFile))
        {
            SqlConnection con = GetCon();
            SqlCommand cmd = new SqlCommand("insertimage", con);
            cmd.Parameters.AddWithValue("@Image", FileUpload1.FileBytes);
            cmd.CommandType = CommandType.StoredProcedure;
            con.Open();
            int result = cmd.ExecuteNonQuery();
            if (result == 1)
            {
                string filename = FileUpload1.FileName;
                FileUpload1.SaveAs(Server.MapPath("~/") + filename);
                imgPicture.ImageUrl = "~/" + filename;
            }
            else 
            {
                lblErrorMsg.Visible = true;
                lblErrorMsg.Text = "Couldn't upload the file! Please try latter.";
            }
        }
        else
        {
            lblErrorMsg.Visible = true;
            lblErrorMsg.Text = "Invalid File, Cannot Upload!";
        }
    }
    else
    {
        lblErrorMsg.Visible = true;
        lblErrorMsg.Text = "Please select a File";
    }
}
 
protected void ibtnRemove_Click(object sender, ImageClickEventArgs e)
{
    imgPicture.ImageUrl = "~/Images/ghost_person.jpg";
}
 
 
protected bool IsImageFile(HttpPostedFile file)
{
    bool isImage = false;
    System.IO.FileStream fs = new System.IO.FileStream(file.FileName, 
      System.IO.FileMode.Open, System.IO.FileAccess.Read);
    System.IO.BinaryReader br = new System.IO.BinaryReader(fs);
    string fileclass = "";
    byte buffer = br.ReadByte();
    fileclass = buffer.ToString();
    buffer = br.ReadByte();
    fileclass += buffer.ToString();
    br.Close();
    fs.Close();
 
    //only allow images    jpg       gif     bmp     png      
    String[] fileType = { "255216", "7173", "6677", "13780" };
    for (int i = 0; i < fileType.Length; i++)
    {
        if (fileclass == fileType[i])
        {
            isImage = true;
            break;
        }
    } 
    return isImage;
}

Using the Database

SQL
CREATE DATABASE [uploadImage];

USE [uploadImage];

CREATE TABLE [dbo].[uploadImg](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [Image] [varbinary](max) NULL,
     CONSTRAINT [PK_uploadImg] PRIMARY KEY CLUSTERED 
    ([ID] ASC)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, 
      IGNORE_DUP_KEY = OFF, AL    LOW_ROW_LOCKS  = ON, 
      ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]) ON [PRIMARY]
GO

CREATE procedure [dbo].[insertimage](@Image varbinary(max)) 
  as insert into uploadImg (Image) values(@Image)
GO

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
India India
I am a 29 year old software Web Developer from Hyderabad, India. I have been working since approximately age 25. Where as in IT Development industry since 27. I am Microsoft Certified Technology Specialist.

I have taught myself in development, beginning with Microsoft's technologies ASP.NET, Approximately 3 years ago, I was given an opportunity to work as a freelance in the tech field. Now I am working as a web developer where my roles make me purely in web based technology solutions which manage and control access to applications and patient information stored in legacy systems, client-server applications.

I too had an opportunity to train some IT professionals with technical skills in development area. Which became my passion.

I have worked on various .NET framework versions(2.0 , 3.5, 4.0) and have been learning every new technology being introduced. Currently, I am looking forward to working in R & D in .Net to create distributed, reusable applications.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Mulukala Lakshmi24-Jul-13 2:18
Mulukala Lakshmi24-Jul-13 2:18 
GeneralMy vote of 4 Pin
Mulukala Lakshmi23-Jul-13 8:18
Mulukala Lakshmi23-Jul-13 8:18 
GeneralMy vote of 4 Pin
sandeepkumarvemula11-Feb-13 22:33
sandeepkumarvemula11-Feb-13 22:33 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.