following code i am able to validate when i select a single image.But how can i change this validation when i want to upload multiple images
C#
[Required]
public BrowsedFile FileToUpload { get; set; }
//how i can change below code when i have list of files
[Required(ErrorMessage = "files should be mime types")]
public string FileContentType =>ContentTypes.TryConvertFromFileExtension(FileToUpload?.FileExtension, FileToUpload?.File.ContentType ?? string.Empty);following list i will be using for multiple image store
C#
[Required]
public IReadOnlyList? ListFiles{get;set:)
Naimish MakwanaRank #324 · 7.7K reputationPosted Jan 18, 2023, 2:25 AM EST
You can create your Custom attribute.
public class AllowedExtensionsAttribute : ValidationAttribute { private readonly string[] _extensions; public AllowedExtensionsAttribute(string[] extensions) { _extensions = extensions; } protected override ValidationResult IsValid( object value, ValidationContext validationContext) { var files = value as IList; foreach(var file in files) { var extension = Path.GetExtension(file.FileName); if (file != null) { if (!_extensions.Contains(extension.ToLower())) { return new ValidationResult(GetErrorMessage(file.FileName)); } } } return ValidationResult.Success; } public string GetErrorMessage(string name) { return $"{name} extension is not allowed!"; } }Then you can use it on property.
[AllowedExtensions(new string[] { ".jpg",".png"})] public IList Photo { get; set; }Source : https://stackoverflow.com/questions/62727427/how-to-validate-uploaded-files-in-asp-net-mvc
Thanks.
Anupam MaitiRank #295 · 8.5K reputationPosted Jan 18, 2023, 4:00 AM EST
We can use the
System.IO.Fileclass to validate the MIME type of multiple selected files.foreach (var file in files) { var fileInfo = new FileInfo(file); if (!IsValidMIMEType(fileInfo.Extension)) { // Do something if the MIME type is not valid } } private bool IsValidMIMEType(string fileExtension) { // Define a list of valid MIME types var validMIMETypes = new List { "image/jpg", "image/jpeg", "image/png", "application/pdf" }; // Get the MIME type of the file based on its file extension var mimeType = MimeMapping.GetMimeMapping(fileExtension); // Return true if the MIME type is in the list of valid MIME types, otherwise return false return validMIMETypes.Contains(mimeType); }Sujeet RamanRank #1,329 · 1.3K reputationPosted Jan 18, 2023, 5:30 AM EST
How can i validate using IValidator object? I need to check file name is empty or not? and the content type and the list is empty or not
need to give validation for
[Required(ErrorMessage = "files should be mime types")] public string FileContentType =>ContentTypes.TryConvertFromFileExtension(FileToUpload?.FileExtension, FileToUpload?.File.ContentType ?? string.Empty);not for list now.Then i need to use
return new() { Name= Name, ContentType = FileContentType, //here each file will come from a foreach of a image list };