Validate max file size during upload in asp.net mvc

Just a quick sketch.

Validation is done as an Attribute (DataAnotations way).

 public class FileAttribute : ValidationAttribute {

        public int MaxContentLength = int.MaxValue;
        public string[] AllowedFileExtensions;
        public string[] AllowedContentTypes;

        public override bool IsValid(object value) {

            var file = value as HttpPostedFileBase;

            //this should be handled by [Required]
            if (file == null)
                return true;

            if (file.ContentLength > MaxContentLength) {
                ErrorMessage = "File is too large, maximum allowed is: {0} KB".FormatWith(MaxContentLength / 1024);
                return false;
            }

            if (AllowedFileExtensions != null) {
                if (!AllowedFileExtensions.Contains(file.FileName.Substring(file.FileName.LastIndexOf('.')))) {
                    ErrorMessage = "Please upload file of type: " + string.Join(", ", AllowedFileExtensions);
                    return false;
                }
            }

            if (AllowedContentTypes != null) {
                if (!AllowedContentTypes.Contains(file.ContentType)) {
                    ErrorMessage = "Please upload file of type: " + string.Join(", ", AllowedContentTypes);
                    return false;
                }
            }

            return true;
        }
    }

And now decorators (within viewmodel).

[Display(Name = "Upload Proof of Address")]
[File(AllowedFileExtensions = new string[] { ".jpg", ".gif", ".tiff", ".png", ".pdf" }, MaxContentLength = 1024 * 1024 * 8, ErrorMessage = "Invalid File")]
public HttpPostedFileBase AddressProof { get; set; }

Hope that helps someone.

Share

Related posts:

  1. LINQ Enumerable.Agregate with Path.Combine
  2. Checkbox has to be ‘checked’ – with unobtrusive jQuery validation and ASP.NET MVC 3
  3. Javascript Encode on server side – Medium Trust Environment
  4. How to implementing log in to site with Facebook account in ASP.NET MVC
  5. Getting ugly with BeginActionLink helper!

4 Responses to “Validate max file size during upload in asp.net mvc”

  1. nachid says:

    That’s really great and thanks for sharing this.
    Just wondering if there is a way to have client side validation also.

  2. David says:

    You are using [int.MaxValue] for the max upload size. It is not true. you have to read the value from the aspnte settings, isn’t it?

  3. Asad says:

    Can u please share the code of your extension method formatwith?? i am newbie thanks in advance

  4. Rafael says:

    Asad, you can use something like that:

    ErrorMessage = String.Format(“File is too large, maximum allowed is: {0} KB”, (MaxContentLength / 1024));

Leave a Response