我正在尝试使用 MVC 中的 HTML FileUpload 控件上传文件。我想验证文件只接受特定的扩展名。我尝试过使用 DataAnnotations 命名空间的 FileExtensions 属性,但它不起作用。请参阅下面的代码 -
public class FileUploadModel
{
[Required, FileExtensions(Extensions = (".xlsx,.xls"), ErrorMessage = "Please select an Excel file.")]
public HttpPostedFileBase File { get; set; }
}
在控制器中,我编写的代码如下 -
[HttpPost]
public ActionResult Index(FileUploadModel fileUploadModel)
{
if (ModelState.IsValid)
fileUploadModel.File.SaveAs(Path.Combine(Server.MapPath("~/UploadedFiles"), Path.GetFileName(fileUploadModel.File.FileName)));
return View();
}
在视图中,我写了下面的代码 -
@using (Html.BeginForm("Index", "FileParse", FormMethod.Post, new { enctype = "multipart/form-data"} ))
{
@Html.Label("Upload Student Excel:")
<input type="file" name="file" id="file"/>
<input type="submit" value="Import"/>
@Html.ValidationMessageFor(m => m.File)
}
当我运行应用程序并提供无效的文件扩展名时,它没有向我显示错误消息。
我知道编写自定义验证属性的解决方案,但我不想使用自定义属性。请指出我哪里出错了。
我遇到了同样的问题,我解决了创建一个新的 ValidationAttribute 的问题。
像这样:
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class FileExtensionsAttribute : ValidationAttribute
{
private List<string> AllowedExtensions { get; set; }
public FileExtensionsAttribute(string fileExtensions)
{
AllowedExtensions = fileExtensions.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
}
public override bool IsValid(object value)
{
HttpPostedFileBase file = value as HttpPostedFileBase;
if (file != null)
{
var fileName = file.FileName;
return AllowedExtensions.Any(y => fileName.EndsWith(y));
}
return true;
}
}
现在,只需使用这个:
[FileExtensions("jpg,jpeg,png,gif", ErrorMessage = "Your error message.")]
public HttpPostedFileBase Imagem { get; set; }
我已经帮忙了。
拥抱!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)