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.
Related posts:
- LINQ Enumerable.Agregate with Path.Combine
- Checkbox has to be ‘checked’ – with unobtrusive jQuery validation and ASP.NET MVC 3
- Javascript Encode on server side – Medium Trust Environment
- Redirect to new domain after rebranding with IIS Url Rewrite Module
- How to implementing log in to site with Facebook account in ASP.NET MVC
-
nachid
-
David
-
Asad
-
Rafael
-
Rrgrgr
