I’m currently creating some custom attributes for doing uploaded file validation.
One of which is a FileSizeAttribute to enforce certain limits (e.g. cannot be bigger than x bytes or smaller than y bytes).
Is there any way I can access the ContentLength property of the HttpPostedFileBase? I was reading a tutorial on file extension validation and the author showed some sample code for simply validating the file extensions.
I’d like to extend to validating the file size client side (in addition to server side) so I can tell them before they even upload if it’s outside of the size limits.
From the code snippet available, it seems like he has access to only the filename:
jQuery.validator.addMethod("fileextensions", function (value, element, param) {
var extension = getFileExtension(value).toLowerCase();
var validExtension = $.inArray(extension, param.fileextensions) !== -1;
return validExtension;
});
Am I wrong here or am I just missing something? I’ve never used jQuery and I have a cursory knowledge of JavaScript, so I don’t really know if this is even possible.
This could be done if the browser supports the File API. It’s a simple matter of querying the
sizeproperty.Here’s an example:
Model:
Controller:
View:
Editor template (
~/Views/Shared/EditorTemplates/HttpPostedFileBase):