How to Upload Image asynchronously in asp.net by c#.

 +Summary

In Asp.net we have File Uploader control which is used for upload image , document and file on server. But it need postback to save on server. Some time this is not feasible solution for uploading image by post back. So In this post we will used Jquery plugin which will help us to upload image asynchronously.

 + Jquery File

Jquery File Uploader file Download From Here

 + AjaxFileUploader.ashx.cs File 

For uploading image asynchronously we will create generic handler in c#. First create generic handler and pest below code.

    /// <summary>
    /// Summary description for AjaxFileUploader
    /// </summary>
    public class AjaxFileUploader : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            if (context.Request.Files.Count > 0)
            {
                string path = context.Server.MapPath("~/images/Temp");
                if (!Directory.Exists(path))
                    Directory.CreateDirectory(path);

                var file = context.Request.Files[0];

                string fileName;

                if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE")
                {
                    string[] files = file.FileName.Split(new char[] { '\\' });
                    fileName = files[files.Length - 1];
                }
                else
                {
                    fileName = file.FileName;
                }
                string strFileName = fileName;
                fileName = Path.Combine(path, fileName);
                file.SaveAs(fileName);

                string msg = "{";
                msg += string.Format("error:'{0}',\n", string.Empty);
                msg += string.Format("msg:'{0}'\n", "images/Temp/"+strFileName);
                msg += "}";
                context.Response.Write(msg);
            }
        }
        public bool IsReusable
        {
            get
            {
                return true;
            }
        }
    }
 + FileUploader.aspx File 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery.js" type="text/javascript"></script>
    <script src="Scripts/ajaxfileupload.js" type="text/javascript"></script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <asp:FileUpload ID="fuProfilePicUpload"  ClientIDMode="Static" runat="server" />
      <div id="divLoader" style="display:none">Please wait.............</div>
      <button id="btnUpload" onclick="return ajaxFileUpload();">Upload</button>
    </div>
    </form>
</body>
</html>
 + JavaScript Code 
<script type="text/javascript">
    function ajaxFileUpload() {

        $("#divLoader").ajaxStart(function () {
            $(this).show();
        }).ajaxComplete(function () {
            $(this).hide();
        });
        $.ajaxFileUpload(
       {
           url: 'AjaxFileUploader.ashx',
           secureuri: false,
           fileElementId: 'fuProfilePicUpload',
           dataType: 'json',
           data: { name: 'logan', id: 'id' },
           success: function (data, status) {
               if (typeof (data.error) != 'undefined') {
                   if (data.error != '') {
                       alert(data.error);
                   } else {
                       alert("Uploaded Successfully");
                   }
               }
           },
           error: function (data, status, e) {
               alert(e);
           }
       }
   )
        return false;
    }
</script>

I hope it will help you :)

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s