Skip to content

Instantly share code, notes, and snippets.

@matthewsinex
Created April 30, 2018 19:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save matthewsinex/87de5e238042dc015abc7a73bf9f120f to your computer and use it in GitHub Desktop.
Save matthewsinex/87de5e238042dc015abc7a73bf9f120f to your computer and use it in GitHub Desktop.
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.");
}
}
@Nitesh4124
Copy link

Screenshot (2)
Screenshot (12)

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