According to the MSDN documentation, by default the FileExtensionsAttribute (.NET 4.5) should allow me to only upload only jpg,jpeg,gif and png files - which is what I want.
I tried uploading a jpg without the attribute, it works. Great. Then I added the attribute to my view model..
[FileExtensions(ErrorMessage = "Please specify a valid image file (.jpg, .jpeg, .gif or .png)")]
public HttpPostedFileBase ImageFile { get; set; }
No joy. The verification fails and the ErrorMessage is shown. On top of that there doesn't seem to be a way to specify any allowed custom file extensions. I ended up extending the FileExtensionsAttribute and using my own verification logic, which works as expected. But why doesn't this way work?
Will post the entire controller and view if required. I used this example as a basis for the uploading logic, but using the DataAnnotations.FileExtensionsAttribute instead of Microsoft.Web.Mvc.FileExtensions.. How do I upload images in ASP.NET MVC?
The FileExtensionsAttribute does not know how to verify a HttpPostedFileBase, so I extended it..
Note that this method forces the file to be a required field. Alternatively, if it is an optional field, use the code below for the method body. This always returns success if no file is specified (probably more correct in most cases)..
Use the Extensions property to set them. Although according to the documentation
You can set it just like you did the
ErrorMessage
. The more likely issue is that it doesn't know how to assess whether theHttpPostedFileBase
has the right extension. You'll need to use the one from the MVC framework or create your own.Since System.ComponentModel.DataAnnotations.FileExtensionsAttribute is sealed. I use a wrapper for MVC 4.
I know this is a bit too late, but perhaps this can help someone out there. This is a modified version of @jfeinour, that will work on the client-side as well: