繁体   English   中英

自定义验证程序不适用于文件上传大小asp.net

[英]custom validator is not working for file upload size asp.net

当用户尝试上传大于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", "");
            }

现在的问题:它没有显示错误消息并且没有验证。 问题出在哪里。

看起来不错,但我认为您忘记了对待attach.HasFile为false的条件,还需要更改条件,因为我们知道1 Byte = 0.000001 MB并且您想通过10MB验证文件长度,所以请执行以下操作处理程序中的更改:

 if (attach.HasFile)
 {
    if ((int)(attach.PostedFile.ContentLength * 0.000001) < 10)
    {
        e.IsValid = true;
    }
    else
    {
        e.IsValid = false;
    }
 }
 else
 {
     e.IsValid = false;
 }

我在您的代码中看到两个问题。 您希望文件大小大于 10MB时验证失败,但是您的代码仅使文件大小小于 10KB才能使验证失败。 这是您应该做的:

if (attach.PostedFile.ContentLength > 10485760) // 10MB = 10 * (2^20)
{
    e.IsValid = false;
}
else
{
    e.IsValid = true;
}

尝试代码

    private const int fileLengthPerMB = 1048576;
    private const int permitedFileSize = 10;
    int postedFileLength = fuHolterDiary.PostedFile.ContentLength;
    if ((postedFileLength / fileLengthPerMB) <= permitedFileSize)
    {
      e.IsValid = true;
    }
    else
    {
      e.IsValid = false;
      lblError.Text = "File size is too large. Maximum size permitted is 10 MB.";                           
    }

您可以通过更改const来更改文件大小

删除ControlToValidate =“ attach”,然后重试。 您不必使用此属性,因为在许多情况下它将不起作用。

您应该做的是直接在验证事件中定位fileUpload控件。 做这样的事情:

protected void FileUploadCustomValidator_ServerValidate(object sender, ServerValidateEventArgs args)
{
    if (fileUpload1.HasFile)
    {
        if (fileUpload1.PostedFile.ContentLength < 4024000) // if file is less than 3.8Mb
        {
            args.IsValid = true;
        }
        else
        {
            args.IsValid = false;
        }
    }

编辑:还可以将事件中的最后一个参数从“ e”更改为“ args”,并在代码块内执行相同的操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM