IFormFile 的数据注释,因此仅允许扩展名为 .png、.jpg 或 .jpeg 的文件

Man*_*a v 6 c# asp.net-core-mvc asp.net-core

我正在使用 ASP.NET Core MVC。我需要 的数据注释/自定义数据注释IFormFile,检查所选/上传的文件是图像,图像的扩展名必须匹配*.png,*.jpg*.jpeg。这是视图模型

public class ProductViewModel 
{
    [Display(Name = "Image")]
    [Required(ErrorMessage = "Pick an Image")]
    //[CheckIfItsAnImage(ErrorMessage = "The file selected/uploaded is not an image")]
    public IFormFile File { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

nhu*_*uvy 1

使用

public class AllowedExtensionsAttribute : ValidationAttribute
{
    private readonly string[] _extensions;

    public AllowedExtensionsAttribute(string[] extensions)
    {
        _extensions = extensions;
    }

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

    public string GetErrorMessage()
    {
        return $"Your image's filetype is not valid.";
    }
}
Run Code Online (Sandbox Code Playgroud)

放入你的代码

public class AllowedExtensionsAttribute : ValidationAttribute
{
    private readonly string[] _extensions;

    public AllowedExtensionsAttribute(string[] extensions)
    {
        _extensions = extensions;
    }

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

    public string GetErrorMessage()
    {
        return $"Your image's filetype is not valid.";
    }
}
Run Code Online (Sandbox Code Playgroud)