52 lines
1.5 KiB
C#
52 lines
1.5 KiB
C#
using FileSignatures;
|
|
using Microsoft.AspNetCore.Http;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
|
|
namespace System.ComponentModel.DataAnnotations;
|
|
|
|
public class ImageFileValidationAttribute : ValidationAttribute
|
|
{
|
|
public ImageFileValidationAttribute(long length)
|
|
{
|
|
Length = length;
|
|
}
|
|
|
|
public long Length { get; set; }
|
|
|
|
protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
|
|
{
|
|
var fileInspector = validationContext.GetRequiredService<IFileFormatInspector>();
|
|
if (null == fileInspector)
|
|
{
|
|
return new ValidationResult("未配置文件验证器");
|
|
}
|
|
if (value is IFormFile file)
|
|
{
|
|
var result = Validate(fileInspector, file);
|
|
if (null != result)
|
|
return result;
|
|
}
|
|
else if (value is IFormFileCollection files)
|
|
{
|
|
foreach (var f in files)
|
|
{
|
|
var result = Validate(fileInspector, f);
|
|
if (null != result)
|
|
return result;
|
|
}
|
|
}
|
|
|
|
return ValidationResult.Success;
|
|
}
|
|
|
|
private ValidationResult? Validate(IFileFormatInspector fileInspector, IFormFile file)
|
|
{
|
|
if (file.Length > Length)
|
|
return new ValidationResult("文件太大");
|
|
var format = fileInspector.DetermineFileFormat(file.OpenReadStream());
|
|
if (null == format)
|
|
return new ValidationResult("文件格式不支持");
|
|
return null;
|
|
}
|
|
}
|