Comment valider type de fichier de HttpPostedFileBase attribut dans Asp.Net MVC 4?

Je suis en train de valider un type de fichier de HttpPostedFileBase attribut de vérifier le type de fichier mais je ne peux pas le faire parce que la validation est de passage. Comment pourrais-je faire cela ?

essayer

Modèle

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

<div class="form-group">
      <label for="@Html.IdFor(model => model.imagem)" class="cols-sm-2 control-label">Escolha a imagem <img src="~/Imagens/required.png" height="6" width="6"></label>
       @Html.TextBoxFor(model => Model.imagem, new { Class = "form-control", placeholder = "Informe a 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 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<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;
}
}
  • Votre ValidateFileAttribute ne doit pas hériter de RequiredAttribute, et vous aussi ne sera pas obtenir la validation côté client. Vous avez besoin pour créer vous-même la validation de l'attribut qui hérite de ValidationAttribute et met en œuvre IClientValidatable.
  • comment pourrais-je faire cela ? avez-vous un exemple ?
  • Mais il est un peu pas clair ce que vous souhaitez valider votre file.ContentLength > 1 * 1024 * 1024 suggèrent que vous voulez une taille maximale de fichier (type de fichier et la taille du fichier de validation sont 2 choses distinctes et doivent être séparer les 2 attributs)