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

匿名 (未验证) 提交于 2019-12-03 01:49:02

问题:

I'm trying validate a file type of HttpPostedFileBase attribute to check type of file but I can't do this because the validation is passing. How could I do this ?

trying

Model

public class EmpresaModel{  [Required(ErrorMessage="Choose a file .JPG, .JPEG or .PNG file")] [ValidateFile(ErrorMessage = "Please select a .JPG, .JPEG or .PNG file")] public HttpPostedFileBase imagem { get; set; }  }

HTML

@Html.TextBoxFor(model => Model.imagem, new { Class = "form-control", placeholder = "Informe a imagem", type = "file" }) @Html.ValidationMessageFor(model => Model.imagem)

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 a valid image public class ValidateFileAttribute : RequiredAttribute{      public override bool IsValid(object value)     {         bool isValid = false;         var file = value as 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 is invalid         }         return isValid;     }      private bool IsOneOfValidFormats(ImageFormat rawFormat)     {         List formats = getValidFormats();          foreach (ImageFormat format in formats)         {             if(rawFormat.Equals(format))             {                 return true;             }         }         return false;     }      private List getValidFormats()     {         List formats = new List();         formats.Add(ImageFormat.        
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!