簡體   English   中英

如何在 ASP.Net MVC 中驗證上傳的文件

[英]How to validate uploaded files in ASP.Net MVC

我在這里有一個很好的答案來驗證僅 1 個文件的文件擴展名和文件大小。

但是如何驗證“List<IFormFile> ImagesFile”的文件擴展名和文件大小?

第一種方法是使用IValidatableObject

public class UserViewModel : IValidatableObject
{
    public IList<IFormFile> Photo { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        var photos = ((UserViewModel)validationContext.ObjectInstance).Photo;
        foreach(var photo in photos)
        {
            var extension = Path.GetExtension(photo.FileName);
            var size = photo.Length;

            if (!extension.ToLower().Equals(".jpg")||! extension.ToLower().Equals(".png"))
                yield return new ValidationResult($"{photo.FileName}'s file extension is not valid.");

            if (size > (5 * 1024 * 1024))
                yield return new ValidationResult($"{photo.FileName}'s file size is bigger than 5MB.");
        }
        
    }
}

結果:

在此處輸入圖像描述 第二種方法是自定義驗證屬性:

最大文件大小屬性:

public class MaxFileSizeAttribute : ValidationAttribute
{
    private readonly int _maxFileSize;
    public MaxFileSizeAttribute(int maxFileSize)
    {
        _maxFileSize = maxFileSize;
    }

    protected override ValidationResult IsValid(
    object value, ValidationContext validationContext)
    {
        var files = value as IList<IFormFile>;
        foreach(var file in files)
        {
            if (file != null)
            {
                if (file.Length > _maxFileSize)
                {
                    return new ValidationResult(GetErrorMessage(file.FileName));
                }
            }
        }    
        

        return ValidationResult.Success;
    }

    public string GetErrorMessage(string name)
    {
        return $"{name}'s size is out of range.Maximum allowed file size is { _maxFileSize} bytes.";
    }
}

AllowedExtensions 屬性:

public class AllowedExtensionsAttribute : ValidationAttribute
{
    private readonly string[] _extensions;
    public AllowedExtensionsAttribute(string[] extensions)
    {
        _extensions = extensions;
    }

    protected override ValidationResult IsValid(
    object value, ValidationContext validationContext)
    {
        var files = value as IList<IFormFile>;
        foreach(var file in files)
        {
            var extension = Path.GetExtension(file.FileName);
            if (file != null)
            {
                if (!_extensions.Contains(extension.ToLower()))
                {
                    return new ValidationResult(GetErrorMessage(file.FileName));
                }
            }
        }
        
        return ValidationResult.Success;
    }

    public string GetErrorMessage(string name)
    {
        return $"{name} extension is not allowed!";
    }
}

Model:

public class UserViewModel
{
    [MaxFileSize(5 * 1024 * 1024)]
    [AllowedExtensions(new string[] { ".jpg",".png"})]
    public IList<IFormFile> Photo { get; set; }
}

查看(上傳.cshtml):

@model UserViewModel

<form method="post"
        asp-action="Upload"
        asp-controller="Home"
        enctype="multipart/form-data">
    <div asp-validation-summary="ModelOnly" class="text-danger"></div>

    <input asp-for="Photo" />
    <span asp-validation-for="Photo" class="text-danger"></span>
    <input type="submit" value="Upload" />
</form>

Controller:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Upload(UserViewModel userViewModel)
{
    if (!ModelState.IsValid)
    {                
        return View("Upload");
    }
    return View("Index");
}

您可以在 model 中使用 IEnumerable HttpPostedFileBase,然后在 controller 上驗證它。 您可以在以下鏈接中找到示例代碼:

asp.net mvc中的多個文件上傳

如果您想在 model 上使用 DataAnnotation,那么我建議您還查看其他鏈接,該鏈接提供有關使用 DataAnnotation 進行自定義驗證的信息

ASP.NET MVC:通過 DataAnnotation 進行自定義驗證

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM