Validate asp fileupload control client side

asp.netclient-sidefile uploadvalidation

i have a asp fileupload control on my page. how to validate the selected file on client side.
validation rules:
1. file must be jpeg,png,bmp or gif.
2. file size must be within 25 kb and 2 mb.
please help.
thanks.
I Have Tried The Following Code to validate the extension

<asp:FileUpload ID="FileUpload2" runat="server"/>                    
<asp:CustomValidator ID="CustomValidator1" runat="server" ClientValidationFunction="ValidateFileUpload" ErrorMessage="Invalid file type. Only .gif, .jpg, .png, .bmp and .jpeg are allowed." ControlToValidate="FileUpload2" ValidationGroup="update">&nbsp;</asp:CustomValidator>
<script language="javascript" type="text/javascript">
    function ValidateFileUpload(Source, args) {
        var fuData = document.getElementById('<%= fuData.ClientID %>');
        var FileUploadPath = fuData.value;

        if (FileUploadPath == '') {
            // There is no file selected
            args.IsValid = false;
        }
        else {
            var Extension = FileUploadPath.substring(FileUploadPath.lastIndexOf('.') + 1).toLowerCase();

            if (Extension == "jpg" || Extension == "jpeg" || Extension == "png" || Extension == "gif" || Extension == "bmp") {
                args.IsValid = true; // Valid file type
            }
            else {
                args.IsValid = false; // Not valid file type
            }
        }
    }
</script>

Best Answer

You cannot determine the size of the file selected in the file input element via client side script. In order to determine the size of the file, one must have read access to the file. As you may imagine, allowing JavaScript to read files on your computer would be a "really bad idea."™

I often see this type of question, and believe that there is some confusion about what the file input element actually does. When the user selects a file, the file bytes aren't "loaded" into this element such that they are available for reading. Rather, the input specifies a reference to the file location so that the browser knows - when the form is posted - to encode the file and send it with the POST. This process is internal to the browser, and isn't exposed to the client in a manner that it can be leveraged by script.

If you need to do file size verification, you should do it on the server where you have access to the actual file bytes. If you are concerned with people "flooding" your site with very large files, you can specify the maximum allowable POST size by configuring your IIS instance.