How to validate file type of HttpPostedFileBase attribute in Asp.Net MVC 4? -


i'm trying validate file type of httppostedfilebase attribute check type of file can't because validation passing. how ?

trying

model

public class empresamodel{  [required(errormessage="choose file .jpg, .jpeg or .png file")] [validatefile(errormessage = "please select .jpg, .jpeg or .png file")] public httppostedfilebase imagem { get; set; }  } 

html

<div class="form-group">       <label for="@html.idfor(model => model.imagem)" class="cols-sm-2 control-label">escolha imagem <img src="~/imagens/required.png" height="6" width="6"></label>        @html.textboxfor(model => model.imagem, new { class = "form-control", placeholder = "informe imagem", type = "file" })        @html.validationmessagefor(model => model.imagem) </div> 

validatefileattribute

using system; using system.collections.generic; using system.componentmodel.dataannotations; using system.drawing; using system.drawing.imaging; using system.linq; using system.web;  //validate file if valid image public class validatefileattribute : requiredattribute{      public override bool isvalid(object value)     {         bool isvalid = false;         var file = value httppostedfilebase;          if (file == null || file.contentlength > 1 * 1024 * 1024)         {             return isvalid;         }          if (isfiletypevalid(file))         {             isvalid = true;         }          return isvalid;     }      private bool isfiletypevalid(httppostedfilebase file)     {         bool isvalid = false;          try         {             using (var img = image.fromstream(file.inputstream))             {                 if (isoneofvalidformats(img.rawformat))                 {                     isvalid = true;                 }              }         }         catch          {             //image invalid         }         return isvalid;     }      private bool isoneofvalidformats(imageformat rawformat)     {         list<imageformat> formats = getvalidformats();          foreach (imageformat format in formats)         {             if(rawformat.equals(format))             {                 return true;             }         }         return false;     }      private list<imageformat> getvalidformats()     {         list<imageformat> formats = new list<imageformat>();         formats.add(imageformat.png);         formats.add(imageformat.jpeg);                 //add types here         return formats;     }   } 

because attribute inherits , existing attribute, need registered in global.asax (refer this answer example), do not in case. validation code not work, , file type attribute should not inheriting requiredattribute - needs inherit validationattribute , if want client side validation, needs implement iclientvalidatable. attribute validate file types (note code if property ienumerable<httppostedfilebase> , validates each file in collection)

[attributeusage(attributetargets.property, allowmultiple = false, inherited = true)] public class filetypeattribute : validationattribute, iclientvalidatable {     private const string _defaulterrormessage = "only following file types allowed: {0}";     private ienumerable<string> _validtypes { get; set; }      public filetypeattribute(string validtypes)     {         _validtypes = validtypes.split(',').select(s => s.trim().tolower());         errormessage = string.format(_defaulterrormessage, string.join(" or ", _validtypes));     }      protected override validationresult isvalid(object value, validationcontext validationcontext)     {         ienumerable<httppostedfilebase> files = value ienumerable<httppostedfilebase>;         if (files != null)         {             foreach(httppostedfilebase file in files)             {                 if (file != null && !_validtypes.any(e => file.filename.endswith(e)))                 {                     return new validationresult(errormessagestring);                 }             }         }         return validationresult.success;     }      public ienumerable<modelclientvalidationrule> getclientvalidationrules(modelmetadata metadata, controllercontext context)     {         var rule = new modelclientvalidationrule         {             validationtype = "filetype",             errormessage = errormessagestring         };         rule.validationparameters.add("validtypes", string.join(",", _validtypes));         yield return rule;     } } 

it applied property as

[filetype("jpg,jpeg,png")] public ienumerable<httppostedfilebase> attachments { get; set; } 

and in view

@html.textboxfor(m => m.attachments, new { type = "file", multiple = "multiple" }) @html.validationmessagefor(m => m.attachments) 

the following scripts required client side validation (in conjunction jquery.validate.js , jquery.validate.unobtrusive.js

$.validator.unobtrusive.adapters.add('filetype', ['validtypes'], function (options) {     options.rules['filetype'] = { validtypes: options.params.validtypes.split(',') };     options.messages['filetype'] = options.message; });  $.validator.addmethod("filetype", function (value, element, param) {     (var = 0; < element.files.length; i++) {         var extension = getfileextension(element.files[0].name);         if ($.inarray(extension, param.validtypes) === -1) {             return false;         }     }     return true; });  function getfileextension(filename) {     if (/[.]/.exec(filename)) {         return /[^.]+$/.exec(filename)[0].tolowercase();     }     return null; } 

note code attempting validate maximum size of file needs separate validation attribute. example of validation attribute validates maximum allowable size, refer this article.

in addition, recommend the complete guide validation in asp.net mvc 3 - part 2 guide creating custom validation attributes


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -