CODEDIGEST
Home Articles CodeDigest Tutorials FAQs
Home > CodeDigest >  
Technologies
 


File Size Validation in FileUpload control in ASP.Net
Submitted By Satheesh Babu B
On 12/20/2008 5:56:44 AM
Tags: asp.net,CodeDigest  

When we build file uploading feature in asp.net we will have requirements to restrict users to upload file above a specified size. By default, JavaScript will not allow us to validate file size or upload files due to security reasons. Hence, it is not possible to validate file size in client side in asp.net when we use FileUpload control.

 

To validate the file size and prevent users from uploading file over a specified size we need to write server side validation function.

 

This little article will help us to achieve this requirement using CustomValidator's server side validation.

 

<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>

 

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.

Recent Codes
  • View All Codes..