0

So I have a few ASP.NET file upload controls in my aspx file -

 <asp:FileUpload ID="fulNature" class="form-control summer" runat="server" /><asp:Labe ID="lblNature" runat="server" Text="Label" Visible="false"></asp:Label>
 <asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="fulNature" Display="Dynamic"
                        ErrorMessage="File size should not be greater than 1 MB." ForeColor="#FF3300" OnServerValidate="ValidateFileSize"></asp:CustomValidator>

<asp:FileUpload ID="fulIndustrial" class="form-control summer" runat="server" /><asp:Label ID="lblIndustrial" runat="server" Text="Label" Visible="false"></asp:Label>
<asp:CustomValidator ID="CustomValidator2" runat="server" ControlToValidate="fulIndustrial" Display="Dynamic"
                        ErrorMessage="File size should not be greater than 1 MB." ForeColor="#FF3300" OnServerValidate="ValidateFileSize"></asp:CustomValidator>

I'm trying to limit file size with one C# validator -

protected void ValidateFileSize(object source, ServerValidateEventArgs args)
{
    var validator = (source as CustomValidator);
    string controlToValidate = validator.ControlToValidate;
    FileUpload SubmittedUpload = validator.NamingContainer.FindControl(controlToValidate) as FileUpload;

    if (SubmittedUpload.FileBytes.Length > 1048576) //  A little padding added.
    {
        args.IsValid = false;
    }
    else
    {
        args.IsValid = true;
    }
}

The issue is that the validator never fires regardless of file size. I have to be missing something simple here, but I'm just not seeing it.

2
  • 2
    it will have to upload the whole file to work. Commented Sep 9, 2014 at 12:48
  • I should have mentioned - the file uploader validator is being used by multiple controls. I edited my question to reflect that. Commented Sep 9, 2014 at 13:12

2 Answers 2

1

you can directly get the size of uploaded file:

long size=fulNature.FileContent.Length;
Sign up to request clarification or add additional context in comments.

1 Comment

How is this different from the answer submitted 6 minutes ago?
0

Try:

long filesize = SubmittedUpload.FileContent.Length;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.