简体   繁体   English

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

[英]FileExtensions attribute of DataAnnotations not working in MVC

I am trying to upload a file using HTML FileUpload control in MVC. 我试图在MVC中使用HTML FileUpload控件上传文件。 I want to validate the file to accept only specific extensions. 我想验证该文件只接受特定的扩展名。 I have tried using FileExtensions attribute of DataAnnotations namespace, but its not working. 我已经尝试使用DataAnnotations命名空间的FileExtensions属性,但它不起作用。 See code below - 见下面的代码 -

public class FileUploadModel
    {
        [Required, FileExtensions(Extensions = (".xlsx,.xls"), ErrorMessage = "Please select an Excel file.")]
        public HttpPostedFileBase File { get; set; }
    }

In the controller, I am writing the code as below - 在控制器中,我正在编写如下代码 -

[HttpPost]
        public ActionResult Index(FileUploadModel fileUploadModel)
        {
            if (ModelState.IsValid)
                fileUploadModel.File.SaveAs(Path.Combine(Server.MapPath("~/UploadedFiles"), Path.GetFileName(fileUploadModel.File.FileName)));

            return View();
        }

In View, I have written below code - 在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)
}

When i run the application and give an invalid file extension, its not showing me the error message. 当我运行应用程序并提供无效的文件扩展名时,它没有显示错误消息。 I am aware of solution to write custom validation attribute, but I dont want to use custom attribute. 我知道编写自定义验证属性的解决方案,但我不想使用自定义属性。 Please point out where I am going wrong. 请指出我哪里出错了。

I had the same problem and I resolved creating a new ValidationAttribute. 我有同样的问题,我解决了创建一个新的ValidationAttribute。

Like this: 像这样:

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

Now, just use this: 现在,只需使用:

[FileExtensions("jpg,jpeg,png,gif", ErrorMessage = "Your error message.")]
public HttpPostedFileBase Imagem { get; set; }

I have helped. 我帮了。 Hugs! 拥抱!

The FileExtensions Attribute does not know how to verify a HttpPostedFileBase. FileExtensions属性不知道如何验证HttpPostedFileBase。 Please try below 请尝试以下

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

In your controller: 在你的控制器中:

[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"});
    }

Like marai answered, the FileExtension Attribute only works on string properties. 与marai回答一样,FileExtension属性仅适用于字符串属性。

In my code, i use the attribute as follows: 在我的代码中,我使用如下属性:

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

Then, in server side, ModelState.IsValid will be false if the postedfile doesn't have the entensions that you specify in the attribute (.zip and .pdf in my example). 然后,在服务器端,如果postedfile没有您在属性中指定的扩展名(在我的示例中为.zip和.pdf),则ModelState.IsValid将为false。

Note: If you are using the HTML.ValidationMessageFor helper to render the error message after PostBack (The File Extension Attribute does not validate on client side, only server side), you need to specify another helper for the FileName property in order to display the extension error message: 注意:如果您使用HTML.ValidationMessageFor帮助程序在PostBack之后呈现错误消息(文件扩展名属性未在客户端验证,仅在服务器端验证),则需要为FileName属性指定另一个帮助程序以显示扩展错误消息:

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

I used the code above in FileExtensions attribute of DataAnnotations not working in MVC , I just did a couple of changes to: 1)avoid namespace collisions and 2) to use IFormFile instead of the original HttpPostedFileBase. 我在DataAnnotations的FileExtensions属性中使用了上面的代码, 而不是在MVC中工作 ,我只做了几处更改:1)避免命名空间冲突和2)使用IFormFile而不是原始的HttpPostedFileBase。 Well, maybe is usefull to someone. 好吧,也许对某人有用。

My code: 我的代码:

[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