Friday, August 3, 2012

Image Upload in Asp.net ( Client Callback )

Introduction

The uploading of the image file is performed by ASP.NET 4.0 Client Callbacks. If you are not familiar with client callbacks  then I suggest that you take a look at ASP.Net AJAX Control Toolkit AsyncFileUpload Control without page refresh or PostBack in ASP.Net Web Page or ASP.Net AJAX Update Panel. The callback is fired as soon as the file is selected by the user using the file field control.
In this article I will explain how to display images that were uploaded using Asp.net file upload control and how to insert the image path into SQL database, Everything is done using  client side JavaScript and  some server side processing.
Let’s first discuss how we are going to accomplish this task. First we need a page ( ImageUpload.aspx ) which will allow the user to select a file. Once, the user has selected the file we upload the file to the server’s folder ( "Images/logo.png" ) and return the user with the url of the image that corresponds to the server’s folder. 
To download sample program Please click here

Step 1:

Before start to design our main page let's a look to my sql database... In my database, called “ImagePath.mdf”, there is a table “image” that has 4 fields. The table structure:  










Add a page file in your web application and name it "ImageUpload.aspx". It will be used to create 2 Textbox,File upload with default image and submit/remove Links. Add following code in the .aspx file: note that ( ViewStateMode="Enabled" )

<%@ Page Title="Home Page" Language="C#" AutoEventWireup="true" ViewStateMode="Enabled"CodeFile="ImageUpload.aspx.cs" Inherits="_Default" %>

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script src="Javascript/JScript.js" type="text/javascript"></script>

<script language="javascript" type="text/javascript">

//javascript for upload Image 

//'btnok' clientback

    function ImageUploadClick() {

        document.getElementById('btnOk').click(); }

</script>

<html xmlns="http://www.w3.org/1999/xhtml">

<head id="Head1" runat="server">

    <title>Yatramate:Registration</title>

    <link href="styles/StyleSheet.css" rel="stylesheet" type="text/css" />

     <style type="text/css">

     .style1 {font-weight: bold; } .style3

     {font-weight: bold; color: #000000; 

      font-family: "Times New Roman", Times, serif;

      width: 273px;}

     .style4{font-family: "Times New Roman", Times, serif;

      width: 273px;}

      .style5{font-family: "Times New Roman", Times, serif;

      font-weight: normal;}

      .style6{font-family: "Times New Roman", Times, serif;

       font-weight: normal; color: #000000; }

      .style8{font-weight: bold; color: #000000;

      font-family: "Times New Roman", Times, serif; width: 249px;}

      .style9{font-family: "Times New Roman", Times, serif;

       width: 249px; }

       .style10 { font-weight: bold;color: #000000;

      font-family: "Times New Roman", Times, serif;

       width: 191px;}

      .style11 { font-family: "Times New Roman", Times, serif;

      width: 191px;}

    </style>

  </head>

<body id="Body1" runat="server" style="background-image: url('images/bgrnd.jpg'); background-repeat:no-repeat;">

    <form id="form1" runat="server">

    <table class="style1">

        <tr><td class="style10">&nbsp;</td>  <td class="style3">

  <br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />

            </td>

            <td class="style5"> &nbsp;</td>

        </tr> <tr> <td class="style10">

                &nbsp;</td>

            <td class="style3">

                Name</td>

            <td class="style5">

       <asp:TextBox ID="txtName" runat="server" BorderColor="#666666" 

        BorderStyle="Solid" BorderWidth="1px" Height="16px" Width="145px"></asp:TextBox>

            </td>  </tr>

        <tr> <td class="style10">

                &nbsp;</td>  <td class="style3"> Organization</td>

            <td class="style5">

         <asp:TextBox ID="txtOrg" runat="server" BorderColor="#666666" 

              BorderStyle="Solid" BorderWidth="1px" Height="16px" Width="145px"></asp:TextBox>

            <br /> </td> </tr>

        <tr><td class="style11">

                &nbsp;</td>

            <td class="style4">

                <span class="style6"><strong>Photo</strong></span><ul><li>

       <asp:Label ID="Label12" runat="server" Text="Upload Photo:" CssClass="Label"></asp:Label>

    </li> <li>  <asp:FileUpload ID="fupPhoto" runat="server"  contenteditable="false" 

        onchange="ImageUploadClick()" CssClass="btnmargin" />

        <asp:Button ID="btnOk" runat="server" BorderStyle="None" 

        CausesValidation="False" CssClass="txtBox" Height="0px" onclick="btnOk_Click1" 

        Text="ok" Width="0px" />

    </li>  <li class="btnmargin">

        <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" 

           onclick="lnkRemove_Click">Remove Photo</asp:LinkButton>

    </li>   </ul>  </td>

            <td class="style5">

          <asp:Image ID="pbPhoto" runat="server" Height="115px" Width="128px" />

           </td> </tr> <tr>

         <td class="style10">

               &nbsp;</td>

          <td class="style3">

         <asp:Button ID="BtnSubmit" runat="server" Text="Submit" 

         onclick="BtnSubmit_Click" style="margin-left: 201px" />

     </td><td class="style8"></td>

   </tr></table>

    </form>

</body>

</html> 

Step 2: 

Before going to code-behind file..create a class file ( C_Image.cs ) under the App_Code folder Following code can be used  to define the size of the image,to determine the image format,determine if landscape or portrait,and set new height and widthof bitmap images.

using System.Drawing; 

using System.Drawing.Imaging;

using System.IO;

using System;

namespace Sample.Content.Items

{

    public class C_Image

    {

        public void ResizeFromStream(string ImageSavePath, int MaxSideSize, Stream Buffer)

        {

            int intNewWidth;

            int intNewHeight;

            Image imgInput = Image.FromStream(Buffer);

            //Determine image format 

            ImageFormat fmtImageFormat = imgInput.RawFormat;

            //get image original width and height 

            int intOldWidth = imgInput.Width;

            int intOldHeight = imgInput.Height;

            //determine if landscape or portrait 

            int intMaxSide;

            if (intOldWidth >= intOldHeight)

            {

                intMaxSide = intOldWidth;

            }

            else

            {

                intMaxSide = intOldHeight;

            }

            if (intMaxSide > MaxSideSize)

            {

                //set new width and height 

                double dblCoef = MaxSideSize / (double)intMaxSide;

                intNewWidth = Convert.ToInt32(dblCoef * intOldWidth);

                intNewHeight = Convert.ToInt32(dblCoef * intOldHeight);

            }

            else

            {

                intNewWidth = intOldWidth;

                intNewHeight = intOldHeight;

            }

            //create new bitmap 

            Bitmap bmpResized = new Bitmap(imgInput, intNewWidth, intNewHeight);

            //save bitmap to disk 

            bmpResized.Save(ImageSavePath, fmtImageFormat);

            //release used resources 

            imgInput.Dispose();

            bmpResized.Dispose();

            Buffer.Close();

         }

    }

}


Step 3:

Now add the code behind in the web page ( ImageUpload.aspx.cs ) where  image needs to be Uploaded. Following code snippet can be used:

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 Sample.Content.Items;

using System.IO;

using System.Data.SqlClient;



public partial class _Default : System.Web.UI.Page

{

    SqlConnection cnn;

    protected void Page_Load(object sender, EventArgs e)

    {

        txtName.Focus();

        cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);

        cnn.Open();//Please check the connection string that i can defined in web.config file

        if (!IsPostBack)

        {   //pls do ViewStateMode="Enabled" in sourse code

            ViewState["image"] = null;

            pbPhoto.ImageUrl = "Images/logo.png";//default image

        }

    }

    public void DeleteTempFile()

    {  // for remove/edit before submit to sql database

        try

        {   if (ViewState["image"] != null)

            {

                FileInfo infoFile = new FileInfo(Server.MapPath("Images/Temp/" + ViewState["image"].ToString()));

                if (infoFile.Exists)

                {

                    FileInfo infoFileMain = new FileInfo(Server.MapPath("Images/" + ViewState["image"].ToString()));

                    if (infoFileMain.Exists)

                    {

                        infoFileMain.Delete();

                    }

                    infoFile.MoveTo(Server.MapPath("Images/" + ViewState["image"].ToString()));

                    FileInfo info = new FileInfo(Server.MapPath("Images/Temp/" + ViewState["image"].ToString()));

                    info.Delete();

                    }

        } }

        catch (Exception ex)

        {  }

    }

    public string AttachmentUpload()

    {

        int i = 0;

        string strFileName = "";

        if (fupPhoto.HasFile)

        {   // check image type/extension/path

            string strPath = Server.MapPath("Images/");

            ViewState["strFileExtensionAttachment"] = Path.GetExtension(fupPhoto.FileName).ToLower();

            ViewState["Title"] = Path.GetFileNameWithoutExtension(fupPhoto.FileName).ToLower();

            string[] allowedExtension = { ".png", ".jpeg", ".jpg", ".bmp", ".gif", ".jpe", ".dib", ".jfif", ".tif", ".tiff" };

            bool isFileOk = false;

            for (int inI = 0; inI < allowedExtension.Length; inI++)

            {

                string str = ViewState["strFileExtensionAttachment"].ToString();

                if (ViewState["strFileExtensionAttachment"].ToString() == allowedExtension[inI])

                {

                    isFileOk = true;

                    break;

                }

            }

            if (isFileOk)

            {

            l1:

                i++;//It will Check File Repetation

                strFileName = i + ViewState["strFileExtensionAttachment"].ToString();

                if (System.IO.File.Exists(strPath + strFileName))

                 goto l1;

                fupPhoto.PostedFile.SaveAs(strPath + strFileName);

                UploadResizeImage("Images/Temp/" + strFileName);

            }

            else

            {

                ViewState["strFileExtensionAttachment"] = null;

            }

        }



        return strFileName;

    }

    private void UploadResizeImage(string Path)

    {   //please check App_Code folder

        //Define the size of images on C_Image.cs class

        if (fupPhoto.PostedFile != null)

        {

            HttpPostedFile myFile = fupPhoto.PostedFile;

            int nFileLen = myFile.ContentLength;

            if (nFileLen > 0)

            {

                C_Image objImage = new C_Image();//please check App_Code folder

                objImage.ResizeFromStream(Server.MapPath(Path), 200, myFile.InputStream);

            }

        }

    }

    public void clearAll()

    {

        txtName.Text = "";

        txtOrg.Text = "";

        ViewState["image"] = null;

        pbPhoto.ImageUrl = "Images/logo.png";

    }

    protected void btnOk_Click1(object sender, EventArgs e)

    {

        ViewState["image"] = AttachmentUpload();//client callback

        if (ViewState["image"] != null && ViewState["image"].ToString() != "")

            pbPhoto.ImageUrl = "Images/Temp/" + ViewState["image"].ToString();

        else

           Response.Write("Invalid file");

    }

    protected void BtnSubmit_Click(object sender, EventArgs e)

    {

        string image;

        if (ViewState["image"] == null)

        {

            image = "Images/logo.png";//default image

        }

        else

        {

            image = "Images/"+ViewState["image"].ToString();//image with path

        }

        string str = "INSERT INTO image VALUES('"+txtName.Text+"','"+txtOrg.Text+"','"+image+"')";

        SqlCommand cmd = new SqlCommand(str, cnn);

        cmd.ExecuteNonQuery();

        Response.Write("<script language='javascript'>alert(' Image Uploaded Successfully...! ')</script language>");

        clearAll();



    }

    protected void lnkRemove_Click(object sender, EventArgs e)

    {

        ViewState["image"] = null;

        pbPhoto.ImageUrl = "Images/logo.png";

    }

}


Step 4:

That's all guys...!
To download sample program Please click here 
the final output will shown like this... eNjOy progRamming..!









Regards @
Shanith Thekkayil
shaanzsster@gmail.com

No comments:

Post a Comment

Twitter Bird Gadget