首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >ASP.NET RC2 IFormFile文件扩展名和文件最大大小自定义验证

ASP.NET RC2 IFormFile文件扩展名和文件最大大小自定义验证
EN

Stack Overflow用户
提问于 2016-07-22 22:04:57
回答 1查看 6.4K关注 0票数 0

我希望在MVC-6 RC2中有自定义的jquery不显眼的验证器。

Old Answer类似,我在This one 中看到了一些RC2示例,但我不知道如何在文件中实现它。

这是我的视图模式

代码语言:javascript
运行
复制
public class FileUploadViewModel
    {
        //TODO [FileType(Validtype="jpeg,png,jif", MaxSize=112222)]// this is what I want
        [Required(ErrorMessage = "Please select a file")]
        public IFormFile File { get; set; }

        [Required(ErrorMessage = "Please select link")]
        public string FileName { get; set; }

        public string ExternalLink { get; set; }

        public string Description { get; set; }    
    }
EN

回答 1

Stack Overflow用户

发布于 2017-06-07 00:01:24

我最终通过使用属性解决了我的问题

下面是我如何创建它的。(我的大小和扩展名都是静态的,在我们的应用程序中也是如此,这就是为什么我在FileTypeAttribute中对其进行了硬编码,但如果您愿意,您可以将其设置为动态,并将其传递给属性构造函数。

代码语言:javascript
运行
复制
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
    public class FileTypeAttribute : ValidationAttribute, IClientModelValidator
    {
        private const int MaxSize = 1048576;
        private const string _DefaultErrorMessage = "Only the following file types are allowed: {0}";
        private IEnumerable<string> _ValidTypes { get; set; }

        public string ValidTypes { get; set; }

        public string ErrorMessageExtension { get; set; }

        public string ErrorMessageSize { get; set; }


        public FileTypeAttribute(string errorExtension, string errorSize)
        {
            ILang lang = ((ContextServiceImpl)ContextService.Instance).HttpContext.RequestServices.GetService(typeof(ILang)) as ILang;
            ErrorMessageExtension = lang[errorExtension];
            ErrorMessageSize = lang[errorSize];

        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            IFormFile file = value as IFormFile;
            if (file != null)
            {

                if (!_ValidTypes.Any(e => file.FileName.EndsWith(e)))
                {
                    return new ValidationResult(ErrorMessageExtension);
                }
                if (file.Length > MaxSize)
                {
                    return new ValidationResult(ErrorMessageSize);
                }
            }

            return ValidationResult.Success;
        }

        public void AddValidation(ClientModelValidationContext context)
        {
            MergeAttribute(context.Attributes, "data-val", "true");
            var errorMessage = FormatErrorMessage(context.ModelMetadata.GetDisplayName());
            MergeAttribute(context.Attributes, "data-val-fileextensions", ErrorMessageExtension);
            MergeAttribute(context.Attributes, "data-val-maxfilesize", ErrorMessageSize);
        }

        private bool MergeAttribute(
        IDictionary<string, string> attributes, string key, string value)
        {
            if (attributes.ContainsKey(key))
            {
                return false;
            }

            attributes.Add(key, value);
            return true;
        }
    }

然后在我的视图模型中,我按如下方式使用属性

代码语言:javascript
运行
复制
public class FileUploadViewModel
    {
         [FileType("invalid format", "invalid size")]
        [Required(ErrorMessage = "Please select a file")]
        public IFormFile File { get; set; }

        [Required(ErrorMessage = "Please select link")]
        public string FileName { get; set; }

        public string ExternalLink { get; set; }

        public string Description { get; set; }    
    }

然后在javascript中这样做。

代码语言:javascript
运行
复制
$.validator.addMethod("fileextensions",
        function (value, element, param) {
            var fileType = $(element)[0].files[0].type;
            var fileTypes = ["image/jpeg", "image/pjpeg", "image/gif", "image/bmp", "image/png", "image/x-png", "image/tiff"]
            var validExtension = $.inArray(type, fileTypes) !== -1;
            return validExtension;
     });

    $.validator.addMethod("maxfilesize",
     function (value, element, param) {

         var fileSize = $(element)[0].files[0].size;
         var maxSize = 1048576;

         var validSize = fileSize < maxSize;
         return validSize;
     });

    $.validator.unobtrusive.adapters.add('fileextensions', [], function (options) {
        var params = {
            fileextensions: $(options.element).data("val-fileextensions").split(',')
        };

        options.rules['fileextensions'] = params;    
        options.messages['fileextensions'] = $(options.element).data("val-fileextensions");

    });

    $.validator.unobtrusive.adapters.add('maxfilesize', [], function (options) {

        options.rules['maxfilesize'] = [];
        options.messages['maxfilesize'] = $(options.element).data("val-maxfilesize");

    });
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38528483

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档