簡體   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