Sunday, November 25, 2012

AsyncFileUpload Control Features


AsyncFileUpload is an ASP.NET AJAX Control that allows you asynchronously upload files to server. The file uploading results can be checked both in the server and client sides.

  • It works within the Update Panel
  • It uploads the file without any postback
  • It provides Client Side and Server side events
  • There are different coloring options for showing file upload. As for example, it shows green color if upload is successful, otherwise it shows red if there is unsuccessful upload.
  • You can show the loading image while file uploading is in progress.
  •  
Just follow the steps

1. Plac the ScriptManager and Register the Ajax control DLL 

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp"%>


2. Now Place the AsyncFileUpload control

<asp:AsyncFileUpload ID="AsyncFileUpload1" Width="400px" runat="server"
OnClientUploadError="uploadError" OnClientUploadStarted="StartUpload"
OnClientUploadComplete="UploadComplete"
CompleteBackColor="Lime" UploaderStyle="Modern"
ErrorBackColor="Red" ThrobberID="Throbber"
onuploadedcomplete="AsyncFileUpload1_UploadedComplete"
UploadingBackColor="#66CCFF" />

3. Let's place the Throbber control to show in the progress image. It is not compulsory to have ThrobberID.
The ThrobberID is only to show the progress of upload.

<asp:Label ID="Throbber" runat="server" Style="display: none">
<img src="../img/progress.gif" align="absmiddle" alt="loading" />
</asp:Label>


4. Place a label to show the Status of upload. this will be updated via Client side Function

<asp:Label ID="lblStatus" runat="server" Style="font-family: Arial; font-size: small;"></asp:Label>


5. Now place the Javascript function in the head section.

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

     function uploadError(sender, args) {
         document.getElementById('lblStatus').innerText = args.get_fileName(), "<span style='color:red;'>" + args.get_errorMessage() + "</span>";
     }

     function StartUpload(sender, args) {
         document.getElementById('lblStatus').innerText = 'Uploading Started.';
     }

     function UploadComplete(sender, args) {
         var filename = args.get_fileName();
         var contentType = args.get_contentType();
         var text = "Size of " + filename + " is " + args.get_length() + " bytes";
         if (contentType.length > 0) {
             text += " and content type is '" + contentType + "'.";
         }
         document.getElementById('lblStatus').innerText = text;
     }
    </script>


6. Write the code at server side below.

protected void AsyncFileUpload1_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
    {
        System.Threading.Thread.Sleep(5000);
        if (AsyncFileUpload1.HasFile)
        {
            string strPath = MapPath(@"~/Uploads/") + Path.GetFileName(e.filename);
            AsyncFileUpload1.SaveAs(strPath);
        }
    }