Daily Archives: April 15, 2013

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: ,,