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
Copy link

Afffgg commented Sep 28, 2020

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

@Nitesh4124
Copy link

Nitesh4124 commented Jan 18, 2022

Screenshot (2)
Screenshot (12)

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