AJAX Control Toolkit Tutorial: AjaxFileUpload - Part Three

Today we will learn about AjaxFileUpload Control of AJAX Control ToolKit Article Series.

As it is Ajax file upload control, which means that files uploaded to server without any Postbacks, refresh or reload of the page ad, it gives a better user experience than the server side postback file controls.

You can learn about my previous parts here:

The best features among this are that they support drag and drop functionality and also you can upload multiple files at a time with maximum size of 1(GB) of file.

Following is the features of Ajax file upload control:

  1. Supports Drag and Drop Functionality
  2. Display File Upload Progress Bar (Depend on support of HTML5 in Browser)
  3. Display the File Info like file size and name of the uploaded file.
  4. Support uploading large file size up to 1 GB
  5. Multiple File Upload support
  6. Client side file chunking

In this modern era almost every browser has a HTML5 compatibility and progress bar is just depend on it, it has a different behavior among the browsers which are either supporting HTML5 or not.

If browser has HTML5 compatible than the progress file upload bar shown in client side, if not supported then it has to wait the server to be ready to accept the file by mean s of polling.

One of the best features of AJAX File Upload Control is Drag and Drop functionality which ease us by drag from any source and drop the control panel. By means of drag and drop you can select the multiple file to be dragged. You can also select multiple file by using keyboard keys like SHIFT or Ctrl key.

Another time consuming thing is to check the file types to be allowed or restricted in code, as we need to get the extension of the file and check correspondingly with code that it supports extension or not by showing custom message in the UI. But now Ajax file upload control bring easiness by using propertyAllowedFileTypes which can check the file types that are allowed to upload. The syntax is easy you have to mention against this property by separating the file extension by comma. Like this jpg, png, gif, docx.

Another good property (MaximumNumberOfFiles) is to allow number of files to be uploaded at a time.
AJAX File upload used handlers to upload the file to the server we will discuss how to add handlers to the configuration file earlier in this article.

AJAX File upload controls the buffers to be uploaded to server by placing the files to the temporary folder and finally when file complete events raise it move the file to the destination path and if SaveAs() is used then it automatically deletes the Temporary files and move to the original destination. If SaveAs() method is not used then you have to call the AjaxFileUploadEventArgs.DeleteTemporaryData() method to delete the temporary file.

There are a Number of Properties, Events and Methods associated with this control we will learn about each one by example.
So let’s start to first handler to the configuration File which will do our task of file uploading to the server.

Setting Up the environment contains adding the handler and also the placing control item to the page.

Adding Handler to the Web Configuration

The AjaxFileUpload control uses an HTTP Handler named AjaxFileUploadHandler.axd This handler has the type AjaxControlToolkit.AjaxFileUploadHandler. You must add this handler to your Web.Config file in order for the AjaxFileUpload control to work.

Here is the code to be placed in <System.Webserver> and inside the <handlers> section.

This Configuration settings is for IIS 7 or higher.

  1. <system.webServer>  
  2.   
  3.     <handlers>  
  4.   
  5.         <add name="AjaxFileUploadHandler" verb="*" path="AjaxFileUploadHandler.axd" type="AjaxControlToolkit.AjaxFileUploadHandler,    
  6.     
  7. AjaxControlToolkit" />  
  8.   
  9.     </handlers>  
  10.   
  11. </system.webServer>  
After Configuring we place the below code to our aspx page which will show the file upload control to the browser.

Firstly we have register the Ajax control toolkit in the page.
  1. <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit"%>  
Then place the code of the control to the page.
  1. <ajaxToolkit:AjaxFileUpload ID="AjaxFileUpload1"OnUploadComplete="AjaxFileUpload1_UploadComplete" Mode="Auto" runat="server"  
  2. />  
After placing this we can view how it looks like in the browser and check its functionality to verify it is working fine.

browser

Now we will verify its functionality by uploading a file.

functionality

Now we will look deeply in to the Properties, Events and Methods.

Properties

 

  • Mode

    It determined how upload progress is displayed. Default value is Auto, the other options are Client and Server. If you have latest version installed and support HTML5 then you have noticed the green progress bar for uploading files and if you have browsers which does not support HTML5 no progress bar shows.

  • Throbber ID

    It is the ID of the control which shown when the file is being uploaded it is the image which shows when upload clicks and it is shown in those browsers which doesn’t support HTML5 API and not in the latest browsers which almost support HTML5 API.

  • Context Keys

    This is the unique ID which identifies the file uploaded in chunks that same file uploaded with that id.
    This is the main communication point which communicate with server while the file is being uploaded. This contains information of the file and other things to be uploaded to the server.

  • MaximumNumberOfFiles

    It restricts the user to not upload files more than mentioned in this property. You can give number(s) like 2, 3 or 5 of files to be uploaded maximum in concurrent fashion. By adding this property we can select one or more file depends on number of files limit write within property.

    You can set this property like this inside your control.

    MaximumNumberOfFiles="2"

    This means that you can upload maximum 2 file(s).

    When user selects the third file it gives alert (“Maximum number of files exceeded”)

    Refer to this screenshot for better understanding.



  • AllowedFileTypes

    This property restrict the user to upload only the set file types to be uploaded. You can set multiple file types by using comma delimiter like this.

    AllowedFileTypes="png,jpeg"

    This is the best option as it reduces your time by not getting the file extension and then checks for it and writes custom code to restrict the user to not upload files of type not mentioned in the list.

    See this is action in screenshot.


  • IsInFileUploadPostBack

    This property is used when you wish to partially postback through this Ajax file upload control.

    This will be true when postback will happen from the control.

    This can be used to avoid execution of unnecessary code during partial postback.

    So can write code in case partial postback called through this control.
    1. protected void Page_Load(object sender, EventArgs e)  
    2. {  
    3.     // check if postback came through AjaxFileUpload control    
    4.     if (AjaxFileUpload1.IsInFileUploadPostBack)  
    5.     {  
    6.         // do for ajax file upload partial postback request    
    7.     }  
    8.     else  
    9.     {  
    10.         // do for normal page request    
    11.     }  
    12. }  
  • OnClientUploadComplete

    This is client function and it is called when single file uploaded successfully to the server. When uploading one or more files it is called all the instances equal to the files uploaded for example if you have uploaded three files then it call thrice times.

    To use this property you have to add OnClientUploadComplete="uploadcomplete" this property to the control. upload complete is the client function and we have to add it to the script file like JavaScript or to use in inline JavaScript script tag like this.
    1. <script type="text/javascript">  
    2.     function uploadcomplete()  
    3.     {  
    4.         alert("successfully uploaded!");  
    5.     }  
    6. </script>  
    Output after using it.

    Output

  • OnClientUploadCompleteAll

    This client function called when all the files that are listed are uploaded successfully.

    OnClientUploadCompleteAll="uploadcompleteAll"
    1. <script type="text/javascript">  
    2.     function uploadcompleteAll()  
    3.     {  
    4.         alert("successfully uploaded All Files!");  
    5.     }  
    6. </script>  


  • OnClientUploadError

    This client function is called when an error occurred while uploading a file to the server.

    OnClientUploadError="uploaderror"
    1. <script type="text/javascript">  
    2.     function uploaderror()  
    3.     {  
    4.         alert("sonme error occured while uploading file!");  
    5.     }  
    6. </script>  
    Kindly see what happens when error occurred,



  • OnClientUploadStart

    This client function is called when file upload  that started is not completed.

    OnClientUploadStart="uploadstart"
    1. <script type="text/javascript">  
    2.     function uploadstart()  
    3.     {  
    4.         alert("upload started from my web app!");  
    5.     }  
    6. </script>  
    See this in action:

This is all about properties now we can move into the next which is Methods.

Methods

  • SaveAs(string filename)

    This method can save the uploaded file to certain directory which you have mentioned in the code. It takes filename as a param to upload it to the server. The good thing about the saveAs method is that it automatically delete all the temporary files data from the server. If you want to use the database system to store image data then you need to call the AjaxFileUploadEventArgs.DeleteTemporaryData() to delete the temporary file.

    I have use this code in my application.
    1. string fileNametoupload = Server.MapPath("~/Documents/") + e.FileName.ToString();    
    2.     
    3. AjaxFileUpload1.SaveAs(fileNametoupload);    
  • CleanAllTemporaryData()

    Delete all temporary uploaded files from temporary folder. It must be called in case you are uploading files to the database as it doesnot remove form temp folders so that after calling this it delete.



    As you can see in this image while file is being uploaded it reside in the temp folder of default file temp path of Ajax file uploader which is C:\Users\yourusername\AppData\Local\Temp\_AjaxFileUpload.

    After that it would be removed as we are calling saveAs method but in the case of file not uploaded through saveAs method it will reside in temp folder.

Events

  • UploadedComplete

    The event raises when a file is uploaded to the server. In this event an instance of AjaxFileUploadEventArgs is passed in the argument that contains file name, size and content type.

    FInd the code of the UploadedComplete Event.

    In control we use this:

    OnUploadComplete="AjaxFileUpload1_UploadComplete"

    And event logic would be:
    1. protected void AjaxFileUpload1_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)  
    2. {  
    3.     string fileNametoupload = Server.MapPath("~/Documents/") + e.FileName.ToString();  
    4.     AjaxFileUpload1.SaveAs(fileNametoupload);  
    5. }  
    This event take AjaxFileUploadEventArgs as param which has lot of properties.

  • UploadedCompleteAll

    This event initializes when all the files successfully uploaded to the server.
    1. protected void AjaxFileUpload1_UploadCompleteAll(object sender, AjaxControlToolkit.AjaxFileUploadCompleteAllEventArgs e)  
    2. {  
    3.     // your code goes here    
    4. }  
  • UploadedStart

    This event raises before uploading any file to the server.
    1. protected void AjaxFileUpload1_UploadStart(object sender, AjaxControlToolkit.AjaxFileUploadStartEventArgs e)  
    2. {  
    3.     // your code goes here    
    4. }  

This is all from Ajax file upload control. Meet you on the next series chapter.

Up Next
    Ebook Download
    View all
    Learn
    View all