篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp EF 4.2 - MVC 3 - 文件验证相关的知识,希望对你有一定的参考价值。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace demo_002.Models
{
public class tblProfile
{
public int Id { get; set; }
public string Name { get; set; }
public string Vorname { get; set; }
[ByteInfo(MaxContentSize = 2)]
public byte[] Bild { get; set; }
[CheckFileInfo(CheckFileExtensions = new string[]{ ".jepg", ".jpg", ".png"})]
public string BildEndung { get; set; }
[CheckFileInfo(CheckContentTypes = new string[]{"image/jpeg","image/png"})]
public string BildType { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace demo_002.Models
{
public class CheckFileInfoAttribute : ValidationAttribute
{
public string[] CheckFileExtensions;
public string[] CheckContentTypes;
public override bool IsValid(object value)
{
var fileInfo = value as string;
if (fileInfo == null)
{
return true; // default is true
}
if (CheckFileExtensions != null)
{
if (!CheckFileExtensions.Contains(fileInfo))
{
ErrorMessage = String.Format("Folgende Formate sind erlaubt : ", string.Join(", ", CheckFileExtensions));
return false;
}
}
if (CheckContentTypes != null)
{
if (!CheckContentTypes.Contains(fileInfo))
{
ErrorMessage = String.Format("Folgende MIME-Typen sind erlaubt : ", string.Join(", ", CheckContentTypes));
return false;
}
}
return base.IsValid(value);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace demo_002.Models
{
public class ByteInfoAttribute : ValidationAttribute
{
// Todo from the web config - set default value
// on the EF model : [ByteInfo (MaxContentSize = 2)]
public int MaxContentSize = 10; // as MB
public override bool IsValid(object value)
{
var binaryInfo = value as byte[];
if (binaryInfo == null)
{
return true; // default is true
}
if (binaryInfo.Length > ((MaxContentSize / 1024) / 1024))
{
ErrorMessage = String.Format("Maximum sind : {0} MB erlaubt", MaxContentSize);
return false;
}
return base.IsValid(value);
}
}
}
以上是关于csharp EF 4.2 - MVC 3 - 文件验证的主要内容,如果未能解决你的问题,请参考以下文章