所以我的aspx文件中有一些ASP.NET文件上传控件 -
<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>
我正试图用一个C#验证器限制文件大小 -
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;
}
}
问题是验证器永远不会触发,无论文件大小如何。我必须在这里遗漏一些简单的东西,但我只是没有看到它。
答案 0 :(得分:1)
您可以直接获取上传文件的大小:
long size=fulNature.FileContent.Length;
答案 1 :(得分:0)
尝试:
long filesize = SubmittedUpload.FileContent.Length;