我想在用户尝试上传大于 10 Mb 的文件时显示错误消息。这是我的验证器代码:
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="File size" ControlToValidate="attach" OnServerValidate="FileUploadCustomValidator_ServerValidate"></asp:CustomValidator>
这是 FileUploadCustomValidator_ServerValidate 的代码:
protected void FileUploadCustomValidator_ServerValidate(object sender, ServerValidateEventArgs e)
{
if (attach.HasFile)
{
if (attach.PostedFile.ContentLength > 10240)
{
e.IsValid = true;
}
else
{
e.IsValid = false;
}
}
}
对于附件:
if (attach.HasFile)
{
attach.PostedFile.SaveAs(Server.MapPath("~/Data/") + attach.FileName);
filename = attach.PostedFile.FileName.ToString();
com.Parameters.AddWithValue("@attach", filename);
}
else
{
com.Parameters.AddWithValue("@attach", "");
}
现在的问题是:它没有显示错误信息,也没有验证。哪里有问题。
最佳答案
我在您的代码中发现了两个问题。如果文件大小大于10MB,您希望验证失败,但只有当文件大小小于时,您的代码才会使验证失败10KB。这是你应该做的:
if (attach.PostedFile.ContentLength > 10485760) // 10MB = 10 * (2^20)
{
e.IsValid = false;
}
else
{
e.IsValid = true;
}
关于c# - 自定义验证器不适用于文件上传大小 asp.net,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44627901/