Search Mallstuffs

Flag Counter
Spirituality, Knowledge and Entertainment




Latest Articles


Move to top
Uploading file asynchronously using Ajax AsyncFileUpload control
Posted By Sarin on Jan 25, 2013     RSS Feeds     Latest Hinduism news
10314 Views

AsyncFileUpload is a control in Asp.Net Ajax control toolkit which supports asynchronous file uploads with drag and drop feature. Features of this control are supported in upgraded browsers like IE 10+, Firefox 8+, Safari 5+, and Google Chrome version 16+. Below are some of the features of this control:
  
AsyncFileUpload Control Features
  1)    One of the most important feature of this control is it compatibility with update panel. We all know that asp.net file upload control does not work with update panel. There is some workaround with .Net file upload control but I am sure you may be looking for a better way of uploading file asynchronously. This Ajax control works within the update panel without any post back.
2)     It has both client side ad server side events which help you in defining custom JavaScript logic or code behind logic for various file upload operations.
3)    Inbuilt color for different status with the flexibility of defining our own color. If file upload successful, green color is shown and if unsuccessful, red color is shown.
4)    We can show custom image or custom text as progress bar while uploading files.
        
AsyncFileUpload Events and Methods
OnUploadComplete -Code-behind method that is invoked after file uploading is complete. This method is generally used to save the file to a particular location.
Point to note about this method is that the uploading starts immediately on selecting the file but the file is not uploaded to any physical location. Instead, it remains in session and is saved to a physical location only after the call to this method is complete
OnClientUploadComplete - This is the JavaScript function to be called for each uploaded file.
OnClientUploadError: This is a client side JavaScript event invoked if some error happened while uploading file.
OnClientUploadStarted: This is the client side function called before the control starts uploading the file onto the server. Note that the uploading starts only after the execution of this function.
SaveAs():  This methods saves the file to a particular location.
  
AsyncFileUpload Properties  

ThrobberID - the ID of a control to be display while uploading is in process. It can either be an image or a simple text control but should necessarily have a runat attribute set to server.
CompleteBackColor - This will be the background color of the control on successful file upload.
UploadingBackColor - This will be the background color of the control till the upload is in progress.
ErrorBackColor: This property will define the background color to be set on unsuccessful upload. Default is "Red".
UploaderStyle: Two default styles of the control ‘Traditional’ and ‘modern’. Default is "Traditional".
HasFile: A Boolean value to indicate if the control has a file or not.

Demo
In this demo, I will use most of the above methods and properties. My control declaration is  

        <ajaxToolkit:AsyncFileUpload ID="AsyncFileUpload1" runat="server" CompleteBackColor="yellow" UploadingBackColor="Green" BackColor="AliceBlue"
OnClientUploadError="uploadError" OnClientUploadStarted="StartUpload" OnClientUploadComplete="UploadComplete" UploaderStyle="Modern" OnUploadedComplete="ProcessUpload" ThrobberID="spanUploading"  />

To demonstrate the use of various javascript events associated with this control, I have additionally added the following HTML controls.
        <span id="spanUploading" runat="server"><img src="ajax-loader.gif" /></span>
        <asp:Label ID="lblStatus" runat="server" Style="font-family: Arial;  
   font-size: small;"></asp:Label>
        <img src="" id="imgUpload" alt="" />  

In the above code, spanUploading will contain the progress image to be shown while uploading the file. It is not mandatory to display only an image as progress. You can replace the image with text or image +text as per your preferences.
  lblStatus will show the details(extension and size) of the uploaded file.
imgUpload will show the uploaded image after the upload is complete.

Below are the javascript functions I have used for this purpose.
  
   function uploadError(sender, args)  {
            document.getElementById('lblStatus').innerText = args.get_fileName(),
   "<span style='color:red;'>" + args.get_errorMessage() + "</span>";
        }

Above function will show the unsuccessful upload error message in lblStatus label  

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

Above function will show the uploading message once the file upload is 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;
        }

Above function will show the content type of the uploaded image and its size.

In code behind, I have saved the selected file to a physical location and then immediately displayed the file in 'imgUpload' control. For this purpose, I have used the script manager to call the javascript code form code behind. This chunk of javascript code will show the uploaded file immediately on its upload.

        protected void ProcessUpload(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
         {
            string filePath = "~/upload/" + e.FileName;
    AsyncUpload.SaveAs(Server.MapPath(filePath));
            //imgUpload.Attributes["src"] = "~/upload/" + e.FileName;
    ScriptManager.RegisterClientScriptBlock(AsyncUpload, AsyncUpload.GetType(), "img","top.document.getElementById('imgUpload').src='upload/" + e.FileName + "';",true);
        }

While uploading the image, my screen looks like
Output

As you see above, my fileupload background color has turned green and I can see the progress image along with the message “uploading started”.
Once the file upload is complete, my screen looks like


As you see above, my fileupload background color has turned yellow and I can see the image content type and size in lblstatus message. Finally, I am also able to see the uploaded image at imgUpload control

For using this control, please make sure that you have set the attributes of the form as  
    <form id="form1" runat="server" enctype="multipart/form-data" method="post">
  
Not setting the enctype attribute may run into some problem like file path returns null.
Sometimes there may be a compatibility issue if the control is used with other version of .Net framework. Set the page ClientIDMode to AutoID to fix this issue.
Or set the following in web.config file
0
<pages  controlRenderingCompatibilityVersion="4.0"  clientIDMode="AutoID"/>
  
AsyncFileUpload Control disadvantages
It also has some disadvantages but ignorable keeping in mind their advantages.  Below are some of its disadvantages:
  1)    Compared to AjaxfileUpload control which supports multiple file upload, this control does not support multiple asynchronous file upload.
2)    Once the file is uploaded, content of the control is not cleared. This control stores the uploaded file information in a session variable. So, even in case of post back, previous file information can be seen in this control.
3)    Like Gmail and yahoo file upload, this file does not give us the flexibility to cancel upload in between.  
4)    Does not have inbuilt support for showing progress of the file uploaded though it can be achieved by custom logic.
          
Conclusion 1
This is an excellent control for uploading file but it has some minor disadvantages which I have stated above. One of the major disadvantage of this control is that it starts uploading immediately on selecting the file. This would be quite annoying if the user has selected wrong file. I feel this control cannot be used with business line applications but would be quite helpful in small application and websites.

0
Note: Images used on this website are either a production of Bhaktivedanta Book Trust(http://www.krishna.com), Iskcon Foundation or were found in google search under "Free to use and share". If any of the images presented here violates copyright issues or infringes anyone copyright or are not under "Fair use", then please bring it to our notice. Read Disclaimer for more.

Share this to your friends. One of your friend is waiting for your share.

Related Articles
Response.Redirect throws _Thread was being aborted_
How to encode and decode HTML request in ASP.NET
Show Update Progress Animation-Ajax
Tips and Tricks with ajax accordion control
Increase performance of your website using caching
How AJAX Works, advantages and disadvantages
Trigger custom or manual postback in ASP.NET
Working with server controls and HMTL controls
Call .net service from javascript
Tips and tricks with ajax calendar

Post Comment




Software developer by profession,
Poet by hobby,
Blogger by Passion
Birth Place: Munger, Bihar
Residence: Mumbai, Maharashtra
Prof exp: 8 years

Read More about me

Read my daily what'sapp quotes
Most Viewed Articles

Latest Spiritual Videos


Latest Funny Videos

Latest News

Latest Social Post
Latest WhatsApp Quotes