✨
This commit is contained in:
@@ -0,0 +1,51 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user