gpt4 book ai didi

c# - 在 EF Code First 模型上进行验证的图像上传

转载 作者:太空宇宙 更新时间:2023-11-03 13:38:09 25 4
gpt4 key购买 nike

我发誓这个问题之前应该已经回答过一百万次了,但在搜索了很长一段时间后我还是一无所获。

我有一个绑定(bind)到对象的 View 。该对象应该以某种方式附加图像(我没有任何首选方法)。我想验证图像文件。我已经看到使用属性执行此操作的方法,例如:

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 模型类中使用这种类型,因为它不太适合数据库存储。

那么最好的方法是什么?

最佳答案

事实证明这是一个非常简单的解决方案。

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

我设置了NotMapped 属性标记,以防止它被保存在数据库中。然后在我的 Controller 中,我在我的对象模型中获取了 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.
}

关于c# - 在 EF Code First 模型上进行验证的图像上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18036810/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com