AsynFileUpload Control and its Validation

AsyncFileUpload is an ASP.NET AJAX Control that allows you asynchronously upload files to server. I got some of idea from here.  In asp.net forum, people are ask query about any file upload control without postback ?. So here it is. For Below I will mention important property both for client side and serve side.

Download complete sample code here.

Important Properties use at client side as below :-

Client Side Property Description
OnClientUploadComplete function executed after the file successfully uploaded
OnClientUploadError executed if the file uploading failed

 

Important Properties use at server side as below :-

Server Side Event Description
OnUploadedComplete when the file successfully uploaded
OnUploadedFileError when the unloaded file is corrupted

Method used to save file at server is SaveAs().

Namespace required :-

using System;

using AjaxControlToolkit;

using System.IO;

 

One Property of AsynFileUpload I like to mention is about ThrobberID. This property is used to display indicator when file is being uploaded. You can add the image to your page and associate the image with the AsynFileUpload property ThrobberID. Note that image   does not directly  points to ThrobberID property, but it will points through  Label control that contains the image (and the Label is hidden with display:none), during the file upload, the image is displayed.  Code will be something like below.

 

<asp:Label runat="server" ID="myThrobber" Style="display: none;">

    <img align="absmiddle" alt="" src="uploading.gif" />

</asp:Label>

 

One more important thing to note about this AsynFileUpload is that, Update Panel is included inside that. So not required to include UpdatePanel. In sort, it does not matter if you put UpdatePanel or not for AsynFileUpload control.

In this demo, I will show you how to upload file to given  path. And provide information about  file as of File Name, File Size, Content Type and Status of file whether its success or not of uploaded file.

Simple Save in Path :-

HTML markup looks like below :-

 

<div>

        <cc1:AsyncFileUpload ID="afuUpload" OnUploadedComplete="afuUpload_UploadedComplete"

            OnUploadedFileError="afuUpload_UploadedFileError" runat="server" OnClientUploadComplete="uploadComplete"

            Width="400px" UploaderStyle="Modern" UploadingBackColor="#CCFFFF" ThrobberID="myThrobber" />

        <asp:Label runat="server" ID="myThrobber" Style="display: none;">

                     <img align="absmiddle" alt="" src="uploading.gif" />

        </asp:Label>

        <br />

        <br />

        <div style="border-style: solid; display: none; width: 350px" id="dvFileInfo">

            <asp:Label ID="lblStatus" Font-Bold="true" runat="server" Text="Status:-" />

<asp:Label ID="lblSuccess" ForeColor="Green" runat="server" /><br />

            <asp:Label ID="lblFileName" Font-Bold="true" runat="server" Text="FileName :-" />

            <asp:Label ID="lblFileNameDisplay" runat="server" /><br />

            <asp:Label ID="lblFileSize" Font-Bold="true" runat="server" Text="File Size :- " />

<asp:Label ID="lblFileSizeDisplay" runat="server" /><br />

            <asp:Label ID="lblContentType" Font-Bold="true" runat="server" Text="Content Type :-" />

<asp:Label ID="lblContentTypeDisplay" runat="server" /><br />

        </div>

        <div style="border-style: solid; display: none; width: 350px" id="dvFileErrorInfo">

            <asp:Label ID="lblErrorStatus" Font-Bold="true" runat="server" Text="Status:-" /><asp:Label

                ID="lblError" ForeColor="Red" runat="server" /><br />

        </div>

</div>

 

I will use JavaScript to display file information, OnClientUploadComplete event where you will get complete file information.

Property Name Description
get_fileName() Return File Name
get_length() Return File Size
get_contentType() Return File Content Type

 

JavaScript uploadError and uploadComplete looks like below one :-

 

JS

 

Server Side code looks like below one :-

 

public void afuUpload_UploadedComplete(object sender, AsyncFileUploadEventArgs e)

{

  try

  {

string savePath = MapPath("~/Uploads/" + Path.GetFileName(e.filename));

      afuUpload.SaveAs(savePath);  

    /*Remeber this below part won't work,so you have to use uploadComplete() of JavaScript where you will

       get file information.*/

      /*

       * lblSuccess.Text = e.state.ToString();

         lblFileName.Text = Path.GetFileName(e.filename);

         lblFileSize.Text = e.filesize;

         lblContentType.Text = afuUpload.ContentType;

      */  

   }

   catch(Exception ex)

   {

       throw ex;

   }             

}  

public void afuUpload_UploadedFileError(object sender, AsyncFileUploadEventArgs e)

{

   //ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "error", "top.$get(\"" + lblErrorStatus.ClientID + "\").innerHTML =

   'Error: " + e.statusMessage + "';", true);

}

 

If you want to display any information using OnUploadedComplete and OnUploadedFileError from server side, its not possible. One work around is that you use ScriptManager RegisterClientScriptBlock().  Commented part above on OnUploadedFileError is one way.

So output like below one :-

Output

 

Validation with AsynFileUpload :-

                 Generally we like to validate or restrict user to upload only particular file extension (e.g. .jpg,.doc).I will do two kind of validation one for file extension and other for file size should not be more then restrict size  Here, I will restrict user to not upload .doc file. More or less code will be same only of above, I just will write addition code which required for validation. However, from download sample code (link provided above) you can get two different files each for simple upload and validation pages.

For validation using AsynFileUpload, you have to validate at two place one at client side and server side.

1) Validation for File Extension :-

 

client side validation has been done at OnClientUploadComplete event.

Extension

 

server side validation done at OnUploadedComplete event.

public void afuUpload_UploadedComplete(object sender, AsyncFileUploadEventArgs e)

{

  try

  {

    string savePath = MapPath("~/Uploads/" + Path.GetFileName(e.filename));

    if (Path.GetExtension(e.filename).Contains(".doc"))

    {

        return;

    }

    afuUpload.SaveAs(savePath);

  }

  catch (Exception ex)

 {

     throw ex;

 }

} 

 

output as below :-

NotEX

2) Validation for File Size :-

client side validation has been done at OnClientUploadComplete event.

FileSizeIMG

             

server side validation done at OnUploadedComplete event.

public void afuUpload_UploadedComplete(object sender, AsyncFileUploadEventArgs e)

{

   try

   {

      string savePath = MapPath("~/Uploads/" + Path.GetFileName(e.filename));

      if (int.Parse(e.filesize) > 3000000)

      {

          return;

       }

       afuUpload.SaveAs(savePath);

   }

   catch (Exception ex)

   {

       throw ex;

   }

}

 

Output like below :-

 

FileSizeRes

 

Hope you will like how to use AsynFileUpload control and how to validate it for particular file extension and file size. Like to hear your feedback for this. (Download source code link provided on top)

30 Comments

  • Great tutorial! &nbsp;I have tried the error handling as you suggested with file sizes and every time I try to get the size of the file in JS, it returns a NaN or when I try to retrieve the context type it returns &quot;&quot;. &nbsp;My AsyncFileUpload control is inside a FormView. &nbsp;I have put it in the Item, Insert and Edit templates and only have the bare bones code behind to get the file and save it to my local machine and it won't do it at all.

  • As this tutorial is about general AsynFileUpload and its validation, not directly related with Formview. Anyway, may be you can post your code at manoj.karkera@gmail.com. I will try to implement the same.

  • Hi Brenden,
    I had created an sample application and mail same to you. Just check it and let me know if you have problem.

  • Adding the following attributes to the tag of my page:

    enctype="multipart/form-data" method="post"

    Fixed the problem. Thanks for the extra help and work!

  • Hi do you have a vb version avilible I tried converting it but I get an error afuUpload not declared !!

  • have you try to convert with given link http://www.developerfusion.com/tools/convert/csharp-to-vb/

    should not be problem after converting from given link

  • Great tutorial! Thank you

  • Welcome Domenico!, happy coding.

  • Hi

    Great tutorial, but is there any way to get the actual filename you saved the file with when you use the SaveAs method. I save the files as a GUID.extension to ensure that I get unique files. Can i get this name and pass it to the client script ?

  • I will tell you what I understood. I think you want file name, form server side you will be at getting at afuUpload_UploadedComplete(..) event. as [e.filename]. and server side you will be getting uploadComplete as [args.get_fileName()]. If you want to get GUID extension, you have to use hidden variable. Assign at server side uploadComplete event, then you will get at this variable at client side uploadComplete event. let me know if you don't get it. Mail me at manoj.karkera@gmail.com for further information

  • Thanks for the guidance. I found it very helpful.

  • Thank you very much for this great tutorial.
    But i a getting an error: "The Controls collection cannot be modified because the control contains code blocks (i.e. )."

    What may cause this problem?

  • I had the same problem with the controls cannot be modified issue. I had a look around and Rick Strahl's site talked about using the # operator to eval at runtime . Although I could get the page to run with Rick's suggestion I was not able to get the sample to work.

    Also on the server side upload complete I was not able to stop the AsyncFileUpload control from uploading the file and I didn't get the UI to update with a message when loading a file with an extension I didn't want to allow.

    Ideas?

  • Hi
    Great tutorial, you say "I will tell you what I understood. I think you want file name, form server side you will be at getting at afuUpload_UploadedComplete(..) event. as [e.filename]. and server side you will be getting uploadComplete as [args.get_fileName()]. If you want to get GUID extension, you have to use hidden variable. Assign at server side uploadComplete event, then you will get at this variable at client side uploadComplete event. let me know if you don't get it."

    How I can store the value in a hidden variable?

    thanks

  • Good job buddy. Thanks for this tutorial.

  • How would I implement an ASP validation, say a dropdownlist item must be selected before file can be uploaded? If I don't want to force the user to make a selection from dropdown before he selects a file, it seems the file gets uploaded any way even he has not made a selection from the dropdown.

  • Not sure about ASP. but if that is ASP.NET then u can make validation like select index of drop down list value is 0 then don't upload file and give user friendly message

  • Thanks! just what i was looking for ! keep posting !

  • want to clear file name after validation returns false

  • Excelente Codigo Compa...

  • Thanks!! Great tutorial!

  • Welcome :)

  • great, it's exactly what i was looking for!! regards from argentina!

  • Welcome :)

  • it is great !it helped me

  • Welcome Dipa, Happy Coding :)

  • Finally, some examples!!! I searched and searched and this is the first complete example that I found today.
    Thank you!

  • Great article... I spent a couple of days trying to display a message after file uploads. All the searching gave me a chance to understand async postback, javascript and such things I did not know. Your in depth article gave a great idea on the inner workings of this control. Thanks a lot!

  • welcome ReginK

  • Thank you! Grate Post. What if people turn off the javascript on browser? Do we have to do a validation on server side?

Comments have been disabled for this content.