Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
ASP.NET Core Multiple File Upload Validation
public class FileAttribute : ValidationAttribute
{
public string[] FileTypes { get; set; }
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value is IFormFile)
{
return ValidateSingleFile((IFormFile)value);
}
else if (value is IEnumerable<IFormFile>)
{
return ValidateMultipleFiles(value);
}
else
{
return new ValidationResult("The input type is not a file.");
}
}
private ValidationResult ValidateSingleFile(IFormFile file)
{
if (!isFileAllowedType(file))
{
return DisallowedFileTypeError(file);
}
return ValidationResult.Success;
}
private ValidationResult ValidateMultipleFiles(object value)
{
IEnumerable<IFormFile> files = (IEnumerable<IFormFile>)value;
foreach (var file in files)
{
if (!isFileAllowedType(file))
{
return DisallowedFileTypeError(file);
}
}
return ValidationResult.Success;
}
private bool isFileAllowedType(IFormFile file)
{
string fileType = file.ContentType.ToLower();
return FileTypes.Length == 0 || FileTypes.Contains(fileType);
}
private ValidationResult DisallowedFileTypeError(IFormFile file)
{
string fileName = file.FileName;
return new ValidationResult($"{ fileName } is not an allowed file type.");
}
}
@Afffgg

This comment has been minimized.

Copy link

@Afffgg Afffgg commented Sep 28, 2020

not my solution........
multiple image upload with length and file type describe in asp.net

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment