如何验证上传的文件在ASP.NET MVC? [英] How to validate uploaded file in ASP.NET MVC?
本文介绍了如何验证上传的文件在ASP.NET MVC?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个创建的动作,它接受一个实体对象和HttpPostedFileBase形象。图像不属于该实体模型
I have a Create action that takes an entity object and a HttpPostedFileBase image. The image does not belong to the entity model.
我可以保存到数据库中,并在磁盘上的文件的实体对象,但我不知道如何验证这些业务规则:
I can save the entity object in the database and the file in disk, but I am not sure how to validate these business rules:
- 是必需的图像
- 内容类型必须是图像/ PNG
- 不得超过1MB
推荐答案
一个自定义的验证属性是一条路可走:
A custom validation attribute is one way to go:
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;
}
}
,然后应用在你的模型:
and then apply on your model:
public class MyViewModel
{
[ValidateFile(ErrorMessage = "Please select a PNG image smaller than 1MB")]
public HttpPostedFileBase File { get; set; }
}
控制器可能是这样的:
The controller might look like this:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel();
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// The uploaded image corresponds to our business rules => process it
var fileName = Path.GetFileName(model.File.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data"), fileName);
model.File.SaveAs(path);
return Content("Thanks for uploading", "text/plain");
}
}
和视图:
@model MyViewModel
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.LabelFor(x => x.File)
<input type="file" name="@Html.NameFor(x => x.File)" id="@Html.IdFor(x => x.File)" />
@Html.ValidationMessageFor(x => x.File)
<input type="submit" value="upload" />
}
这篇关于如何验证上传的文件在ASP.NET MVC?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文