File upload validation in ASP.NET MVC

One of the beauties of ASP.NET MVC is model validation. Just attach the attributes from the System.ComponentModel.DataAnnotations namespace to the properties of your model or view-model, and you magically have a working validation without messing up your code.

This works perfectly if you have a simple property, like a string or a number, but you won’t find too much help for validating uploaded files in this namespace. From .NET 4.5 there is a FileExtensionAttribute, but usually a more thorough check is requested.

What you always have to check:

  • Is any file uploaded?
  • The extension of the uploaded file is valid?
  • The size of the uploaded file falls within the accepted range?

Sometimes you also have to check:

Let’s create your own validation attribute! Just make sure you derive your custom attribute class from the ValidationAttribute base class and apply it to HttpPostedFileBase properties in the model.

This is a working solution:

[AttributeUsage( AttributeTargets.Property )]
public sealed class AttachmentAttribute : ValidationAttribute
  protected override ValidationResult IsValid( object value, 
ValidationContext validationContext ) { HttpPostedFileBase file = value as HttpPostedFileBase; // The file is required. if( file == null ) { return new ValidationResult( "Please upload a file!" ); } // The meximum allowed file size is 10MB. if( file.ContentLength > 10 * 1024 * 1024 ) { return new ValidationResult( "This file is too big!" ); } // Only PDF can be uploaded. string ext = Path.GetExtension( file.FileName ); if( String.IsNullOrEmpty( ext ) || !ext.Equals( ".pdf", StringComparison.OrdinalIgnoreCase ) ) { return new ValidationResult( "This file is not a PDF!" ); } // Everything OK. return ValidationResult.Success; } }

Just add the [Attachment] attribute to the appropriate properties of the model, and your validation errors will land in the ModelState.

If your app allows uploading different files on different pages, you can create an enum for the different file types and pass that enum to the constructor of the AttachmentAttribute. This way you can centralize the file validation logic in your website.

What else do you usually check when you validate the uploaded files?


Technorati-címkék: ,,

7 thoughts on “File upload validation in ASP.NET MVC

  1. Pingback: Ajax file upload | Codes from the field

  2. Jett


    I am getting null for the parameter object value. What am I missing here?

    I am using MVC5 and following are lines from my ViewModel:

    public HttpPostedFileBase FileAttachment { get; set; }


    1. Jett

      Never mind got it working. I don’t have the FileAttachment property in [Bind(Include = “…”)] in my controller. Thanks for this great solution.

  3. walter

    idk why its not working the validation, i have attached the attribute to property, but is not called, even when i try to upload without select any file or file is wring extension…. idk what to do😦


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s