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)

Published Friday, October 16, 2009 10:02 PM by Manoj karkera
Filed under:

Comments

# re: AsynFileUpload Control and its Validation

Tuesday, November 3, 2009 3:19 PM by b471code3

Great tutorial!  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 "".  My AsyncFileUpload control is inside a FormView.  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.

# re: AsynFileUpload Control and its Validation

Tuesday, November 3, 2009 10:42 PM by Manoj karkera

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.

# re: AsynFileUpload Control and its Validation

Friday, November 6, 2009 12:48 AM by Manoj karkera

Hi Brenden,

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

# re: AsynFileUpload Control and its Validation

Monday, November 16, 2009 10:46 AM by b471code3

Adding the following attributes to the <form> tag of my page:

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

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

# re: AsynFileUpload Control and its Validation

Thursday, January 21, 2010 1:04 PM by mike

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

# re: AsynFileUpload Control and its Validation

Thursday, January 21, 2010 10:12 PM by Manoj karkera

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

should not be problem after converting from given link

# re: AsynFileUpload Control and its Validation

Thursday, January 21, 2010 10:14 PM by Manoj karkera

have you try to convert with given link www.developerfusion.com/.../csharp-to-vb   should not be problem.

# re: AsynFileUpload Control and its Validation

Monday, January 25, 2010 5:05 AM by Domenico Dell'Olio

Great tutorial! Thank you

# re: AsynFileUpload Control and its Validation

Monday, January 25, 2010 5:24 AM by Manoj karkera

Welcome Domenico!, happy coding.

# re: AsynFileUpload Control and its Validation

Wednesday, January 27, 2010 12:32 PM by Niall M

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 ?

# re: AsynFileUpload Control and its Validation

Wednesday, January 27, 2010 9:48 PM by Manoj karkera

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

# re: AsynFileUpload Control and its Validation

Thursday, February 18, 2010 9:08 PM by jdk (an appreciative Aussie)

Thanks for the guidance. I found it very helpful.

# re: AsynFileUpload Control and its Validation

Thursday, April 1, 2010 8:38 AM by gorkem

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?

# re: AsynFileUpload Control and its Validation

Wednesday, June 2, 2010 11:14 AM by bevans

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?

# re: AsynFileUpload Control and its Validation

Wednesday, June 9, 2010 1:37 PM by Benito Colón

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

# re: AsynFileUpload Control and its Validation

Wednesday, September 1, 2010 3:32 AM by sobinscott

Good job buddy. Thanks for this tutorial.

# re: AsynFileUpload Control and its Validation

Friday, November 12, 2010 11:18 AM by NoBullMan

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.

# re: AsynFileUpload Control and its Validation

Friday, November 12, 2010 3:43 PM by Manoj karkera

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

# re: AsynFileUpload Control and its Validation

Sunday, November 14, 2010 7:14 PM by Sebastián

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

# re: AsynFileUpload Control and its Validation

Monday, December 13, 2010 4:46 AM by roma

want to clear file name after validation returns false

# re: AsynFileUpload Control and its Validation

Friday, December 24, 2010 11:35 AM by jhohan vasquez(jhohan25@hotmail.es)

Excelente Codigo Compa...

# re: AsynFileUpload Control and its Validation

Tuesday, January 25, 2011 5:39 AM by Bruce Talcott

Thanks!! Great tutorial!

# re: AsynFileUpload Control and its Validation

Tuesday, January 25, 2011 10:46 AM by Manoj karkera

Welcome :)

# re: AsynFileUpload Control and its Validation

Sunday, January 30, 2011 1:38 PM by Juan Manuel Figueroa Bailon

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

# re: AsynFileUpload Control and its Validation

Sunday, January 30, 2011 7:58 PM by Manoj karkera

Welcome :)

# re: AsynFileUpload Control and its Validation

Tuesday, March 8, 2011 12:52 AM by Dipa Bhansali

it is great !it helped me

# re: AsynFileUpload Control and its Validation

Tuesday, March 8, 2011 10:39 AM by Manoj karkera

Welcome Dipa, Happy Coding :)

# re: AsynFileUpload Control and its Validation

Saturday, April 23, 2011 7:57 AM by Predrag

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

Thank you!

# re: AsynFileUpload Control and its Validation

Wednesday, May 4, 2011 9:50 AM by ReginK

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!

# re: AsynFileUpload Control and its Validation

Monday, May 9, 2011 12:11 PM by Manoj karkera

welcome ReginK

# re: AsynFileUpload Control and its Validation

Thursday, April 26, 2012 10:27 AM by etlds

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