Tuesday, April 19, 2011

File Size Validation in FileUpload control in ASP.NET

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="FileUpload1" runat="server" />
            <asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="FileUpload1"
                ErrorMessage="File size should not be greater than 1 KB." OnServerValidate="CustomValidator1_ServerValidate"></asp:CustomValidator>

..........

protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
    {
        if (FileUpload1.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.

No comments:

Post a Comment

Ajax CalendarExtender displaying at wrong position in Chrome

< script type ="text/javascript" language ="javascript">     function onCalendarShown(sender, args)...