Wednesday 19 March 2014

AJAX Image Upload in Asp.net C#

We've got a sweet solution that uploads an image with AJAX and then immediately displays.

Ajax ,an acronym for Asynchronous Javascript and Xml is a group of interrelated web development techniques used on the client side to create asynchronous web applications.With Ajax, web applications can send data to, and retrieve data from, a server asynchronously (in the background) without interfering with the display and behavior of the existing page.

Here we are using ajaxupload.js to upload an image and show upload button on mouse hover and mouse out same like facebook.

On mouse out hide upload button
Screen 1


On Mouse hover show upload button

On mouse hover show upload button
Screen 2

Choose image file

choose image file
Screen 3

Finally Preview of image without postback (without refreshing page)

Upload image without postback
Screen 4

JS :

You need this following javascript file to perform AJAX Image Upload they are following:

  • jquery-1.7.2.min.js

  • ajaxupload.js

HTML:

<div align="center" style="width: 100%; height: auto;">
        <div style="width: 960px; height: auto;">
            <div style="background-color: #eee; border: 1px solid #CCC;">
                <h1>
                    AJAX Image Upload in Asp.net C#</h1>
                <h4>
                    Contains front-end (jQuery) and back-end code (c#) to upload an image and display
                    the same image on screen.</h4>
                <div align="left">
                    <h4 style="margin-left: 60px;">
                        > On Mouse hover show upload button</h4>
                    <h4 style="margin-left: 60px;">
                        > On Mouse out hide upload button</h4>
                </div>
                <div style="width: auto; height: auto; margin-top: 45px; margin-bottom: 50px; margin-left: 420px;
                    overflow: hidden;">
                    <div class="pic" style="float: left; height: 160px; width: 150px; border: 1px solid #CCC;">
                        <img id="imgUser" height="160" width="150" src="Images/NoPhotoAvailable.jpg" runat="server" />
                        <div align="center" style="height: 23px; z-index: 5; width: auto; position: absolute;
                            bottom: 0px; right: 0px;">
                            <asp:Button ID="btnUpload" ValidationGroup="vgUploadImage" runat="server" Text="Upload"
                                class="btn-update" Style="border: 0px; width: 69px; height: 23px; margin: 0px;
                                background-color: #93bbe1;" />
                        </div>
                    </div>
                </div>
                <div style="width: auto; height: 80px; margin-left: 35px;">
                    <div style="height: 25px; width: auto;">
                        <asp:Label runat="server" ID="lblImageMsg"></asp:Label>
                        <asp:TextBox ID="txtImage" placeholder="Image name come here" runat="server" Style="height: 30px;
                            font-size: 16px; width: 250px;"></asp:TextBox>
                    </div>
                </div>
            </div>
        </div>
    </div>

Script :

//Ajax Upload Script
        $(function() {
            new AjaxUpload('#<%=btnUpload.ClientID %>', {
                action: 'UploadHandler.ashx?Image=True',
                onComplete: function(file, response) {
                    debugger;
                    if (response != null) {
                        $('#<%=imgUser.ClientID %>').attr('src', response.toString());
                        document.getElementById("<%=txtImage.ClientID %>").value = file.toString();
                    }
                    else {
                        alert('Response is null!!!');
                    }
                },
                onSubmit: function(file, ext) {
                    if (!(ext && /^(jpeg|png|gif|bmp|jpg)$/i.test(ext))) {
                        alert('Invalid Image Format.');
                        return false;
                    }
                }
            });
        });

// If you don't want to show upload button on mouse hover and out just remove this code.

//On mouse hover and mouse out show/hide button code
        $(document).mousemove(function(e) {
            var $targ = $(e.target);
            if ($targ != "") {
                if ($targ.closest('.pic').length || $targ.is('.pic').length || $targ.closest('input[type=file]').length || $targ.is('input[type=file]').length) {
                    $('#<%=btnUpload.ClientID %>').show();
                }
                else {
                    $('#<%=btnUpload.ClientID %>').hide();
                }
            }
        });

Handler Code :

if (context.Request.QueryString["Image"] != null && context.Request.QueryString["Image"].ToString() != "")
        {
            if (context.Request.Files[0] != null && context.Request.Files[0].ToString() != "")
            {
                HttpPostedFile postedFile = context.Request.Files[0];

                string ImagePath = "UploadedImage/";
                postedFile.SaveAs(System.Web.HttpContext.Current.Server.MapPath(ImagePath) + postedFile.FileName.ToString());

                context.Response.Write(ImagePath + postedFile.FileName.ToString());
                context.Response.End();
            }
        }

Download Link :

Download Complete Project

Enjoyed this post? Share and Leave a comment below, thanks! :)

No comments:

Post a Comment