Question

I followed this tutorial to create validation on HttpPostedFileBase, it works if I use HttpPostedFileBase, but if I changed to IEnumerable<HttpPostedFileBase> for uploading multiple files, and submit the form the ModelState.IsValid is always false. I uploaded .png file and size is 914 bytes. How to use data annotation to validate multiple file upload?

My Model

public class BillingViewModel
{
     [Required]
     public long BillingID { get; set; }    
     public IEnumerable<TimeKeeper> TimeKeepers { get; set; }    
     [Required]
     [ValidateFile]
     public IEnumerable<HttpPostedFileBase> PostedFiles { get; set; }
}

ValidateFile.cs:

public class ValidateFileAttribute : ValidationAttribute
    {
        public override bool IsValid(object value)
        {
            int MaxContentLength = 1024 * 1024 * 3; //3 MB
            string[] AllowedFileExtensions = new string[] { ".jpg", ".gif", ".png", ".pdf" };
            var file = value as HttpPostedFileBase;

            if (file == null)
            {
                return false;
            }
            else if (!AllowedFileExtensions.Contains(file.FileName.Substring(file.FileName.LastIndexOf('.'))))
            {
                ErrorMessage = "Please upload Your Photo of type: " + string.Join(", ", AllowedFileExtensions);
                return false;
            }
            else if (file.ContentLength > MaxContentLength)
            {
                ErrorMessage = "Your Photo is too large, maximum allowed size is : " + (MaxContentLength / 1024).ToString() + "MB";
                return false;
            }
            else
            {
                return true;
            }
        }
    }
Was it helpful?

Solution

It looks like you are casting the property to the wrong type.

Change this:

var file = value as HttpPostedFileBase;

to:

var files = value as IEnumerable<HttpPostedFileBase>;

and then you can iterate through each item in the collection and validate each file is the correct size.

OTHER TIPS

Can you do something like

[Required]
public int? ListCount
{
 get {return PostedFiles == null || PostedFiles.Count()==0? (int?)null: PostedFiles.Count();}
}

Catch: Won't work on client side

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top