上传前的图像宽度/高度的客户端验证,ASP.NET MVC5

时间:2015-06-09 13:18:15

标签: jquery asp.net-mvc unobtrusive-validation

我正在尝试在上传之前验证图像的宽度和高度。 我创建了一个验证属性,服务器端按预期工作,但我无法修复客户端验证。

这是自定义验证属性

public class ImageDimensionsAttribute : ValidationAttribute, IClientValidatable
    {
        private readonly int _width;
        private readonly int _height;
        private readonly string _dims;

        public ImageDimensionsAttribute(int width, int height)
        {
            _width = width;
            _height = height;
            _dims = String.Format("{0},{1}", _width, _height);
        }

        public override bool IsValid(object value)
        {
            if (value == null) return true;
            var file = value as HttpPostedFileBase;

            using (var img = Image.FromStream(file.InputStream))
            {
                return img.Width <= _width && img.Height <= _height;
            }
        }

        public override string FormatErrorMessage(string name)
        {
            return string.Format(Messages.InvalidImageDimensions, _width, _height);
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule
            {
                ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
                ValidationType = "imagedimensions"
            };
            rule.ValidationParameters.Add("dims", _dims);
            yield return rule;
        }
    }

和我的javascript

$(function () {
        $.validator.addMethod("imagedimensions", function (value, element, params) {
            if (value == null)
                return true;

            var file = element.files[0];           
            var reader = new FileReader();
            var image = new Image();
            var sizes = params.split(",");
            var maxWidth = parseInt(sizes[0]);
            var maxHeight = parseInt(sizes[1]);

            var result = false;
            reader.readAsDataURL(file);
            reader.onload = function (_file) {
                image.src = _file.target.result;                
                image.onload = function () {
                    var w = this.width,
                        h = this.height
                    console.log(w, h);
                    if (w > maxWidth || h > maxHeight) {
                        return false;
                    } else {                        
                        console.log("i am valid size but validator can not await");
                        return true;
                    }
                };                
            };
        });        

        $.validator.unobtrusive.adapters.addSingleVal("imagedimensions", "dims");
    }(jQuery));

似乎javascript函数不等待reader.onload执行所以它总是返回false - 一切都无效。我正在寻找一种方法来制作javascript&#34; await&#34;。

0 个答案:

没有答案