繁体   English   中英

DataAnnotations的FileExtensions属性在MVC中不起作用

[英]FileExtensions attribute of DataAnnotations not working in MVC

我试图在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();
        }

在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; }

我帮了。 拥抱!

FileExtensions属性不知道如何验证HttpPostedFileBase。 请尝试以下

[FileExtensions(Extensions = "xlsx|xls", ErrorMessage = "Please select an Excel file.")]
public string Attachment{ get; set; }

在你的控制器中:

[HttpPost]
    public ActionResult Index(HttpPostedFileBase Attachment)
    {
        if (ModelState.IsValid)
        {
            if (Attachment.ContentLength > 0)
            {
                string filePath = Path.Combine(HttpContext.Server.MapPath("/Content/Upload"), Path.GetFileName(Attachment.FileName));
                Attachment.SaveAs(filePath);
            }
        }
        return RedirectToAction("Index_Ack"});
    }

与marai回答一样,FileExtension属性仅适用于字符串属性。

在我的代码中,我使用如下属性:

public class MyViewModel
{
    [Required]
    public HttpPostedFileWrapper PostedFile { get; set; }

    [FileExtensions(Extensions = "zip,pdf")]
    public string FileName
    {
        get
        {
            if (PostedFile != null)
                return PostedFile.FileName;
            else
                return "";
         }
    }
}

然后,在服务器端,如果postedfile没有您在属性中指定的扩展名(在我的示例中为.zip和.pdf),则ModelState.IsValid将为false。

注意:如果您使用HTML.ValidationMessageFor帮助程序在PostBack之后呈现错误消息(文件扩展名属性未在客户端验证,仅在服务器端验证),则需要为FileName属性指定另一个帮助程序以显示扩展错误消息:

@Html.ValidationMessageFor(m => m.PostedFile)
@Html.ValidationMessageFor(m => m.FileName)

我在DataAnnotations的FileExtensions属性中使用了上面的代码, 而不是在MVC中工作 ,我只做了几处更改:1)避免命名空间冲突和2)使用IFormFile而不是原始的HttpPostedFileBase。 好吧,也许对某人有用。

我的代码:

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class FileVerifyExtensionsAttribute : ValidationAttribute
{
    private List<string> AllowedExtensions { get; set; }

    public FileVerifyExtensionsAttribute(string fileExtensions)
    {
        AllowedExtensions = fileExtensions.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
    }

    public override bool IsValid(object value)
    {
        IFormFile file = value as IFormFile;

        if (file != null)
        {
            var fileName = file.FileName;

            return AllowedExtensions.Any(y => fileName.EndsWith(y));
        }

        return true;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM