Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Uploading an Image and Displaying It on the UI Page

4.86/5 (7 votes)
18 Dec 2012CPOL 41K  
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)