Home > ASP.Net > Validate FileUpload Size

Validate FileUpload Size


Hi

try this example to validate FileUpload size

<asp:FileUpload ID="fuFile" runat="server" />

<asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="fuFile"
   ErrorMessage="File size should not be greater than 1 KB." OnServerValidate="CustomValidator1_ServerValidate"></asp:CustomValidator>

 in code behind:

protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
    {
        if (fuFile.FileBytes.Length > 1024)
        {
            args.IsValid = false;
        }
        else
        {
            args.IsValid = true;       
        }

    }

The above code will prevent users to upload file with size more than 1 KB.

Good Luck

Advertisements
Categories: ASP.Net Tags:
  1. Rick
    March 19, 2009 at 1:34 am

    This still only works if the filesize is below the “maxRequestLength” attribute in web.config. I need to validate against files above the “maxRequestLength” value.

  2. yasserzaid
    March 19, 2009 at 7:20 am

    Hi Rick

    Thank you for your comment but if you read this post again you will find that i validate that user can’t upload file with size larger than 1 m

    yes you can set maxRequestLength in you web.config file

    Good Luck

    YZ

  3. eric
    March 20, 2009 at 9:27 am

    We can set the maxRequestLength to max value: 2097151
    then use above code to verify the upload file size.

    These are still have 2 disadvantages:
    1. The upload file cannot large than 2097151 bytes (it’s enough I think)
    2. If the file is very large (ex. 1G), it’s take a lot of time to get the result)

  4. eric
    March 20, 2009 at 9:40 am

    I like to write the code to:

    args.IsValid = fuFile.FileBytes.Length < 1024;

  5. yasserzaid
    March 20, 2009 at 11:53 am

    Hi eric

    Thank you for your comments

    and you are correct

    you can write code for custom validator like that

    args.IsValid = fuFile.FileBytes.Length < 1024;

    Good Luck

    and hope my post helps you

  6. Arun
    April 16, 2009 at 5:42 pm

    Hi,

    Thanks for ur solution.

  7. yasserzaid
    April 17, 2009 at 11:22 am

    You are welcome Arun

    Hope this helps

    Good Luck

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: