2

我可以发誓,这应该已经回答了一百万次之前,但我搜索了一段时间后空了。图片上传,验证EF代码优先模型

我有一个视图绑定到一个对象。这个对象应该有一个附加到它的图像(我没有任何首选的方法)。我想验证图像文件。我见过的方式与属性要做到这一点,例如:

public class ValidateFileAttribute : RequiredAttribute 
{ 
    public override bool IsValid(object value) 
    { 
     var file = value as HttpPostedFileBase; 
     if (file == null) 
     { 
      return false; 
     } 

     if (file.ContentLength > 1 * 1024 * 1024) 
     { 
      return false; 
     } 

     try 
     { 
      using (var img = Image.FromStream(file.InputStream)) 
      { 
       return img.RawFormat.Equals(ImageFormat.Png); 
      } 
     } 
     catch { } 
     return false; 
    } 
} 

然而,这需要HttpPostedFileBase对房地产模型类型:

public class MyViewModel 
{ 
    [ValidateFile(ErrorMessage = "Please select a PNG image smaller than 1MB")] 
    public HttpPostedFileBase File { get; set; } 
} 

这一切都很好,但我不能在EF Code First模型类中使用这种类型,因为它不适合数据库存储。

那么最好的方法是什么?

+1

是的,这是有一个My ** ViewModel **的整个点。你在你的视图中使用你的ViewModels。而且你为你的实体创建了不同的类型,并且你手动或者像Automapper这样做了它们之间的映射。 – nemesv

+0

我以前没有听说过(我只是MVC开发的几天)。我实际上想到了另一个解决方案,为我工作。我把它贴在 – Inrego

+0

以下但是对于所有模型来说,ViewModels并不是很多额外的工作吗?这难道不是干掉干的做事方式的目的吗? – Inrego

回答

-1

当我远一点与网站的发展,这是不可避免的,我开始使用的ViewModels。为每个视图创建一个模型肯定是要走的路。

2

原来这是一个相当简单的解决方案。

public class MyViewModel 
{ 
    [NotMapped, ValidateFile(ErrorMessage = "Please select a PNG image smaller than 1MB")] 
    public HttpPostedFileBase File { get; set; } 
} 

我设置了NotMapped属性标记,以防止它被保存在数据库中。然后在我的控制,我得到的HttpPostedFileBase在我的对象模型:

public ActionResult Create(Product product) 
    { 
     if (!ModelState.IsValid) 
     { 
      return View(product); 
     } 
     // Save the file on filesystem and set the filepath in the object to be saved in the DB. 
    }