Get file size, image width and height before upload

前端 未结 7 1253
自闭症患者
自闭症患者 2020-11-22 03:50

How can I get the file size, image height and width before upload to my website, with jQuery or JavaScript?

7条回答
  •  太阳男子
    2020-11-22 04:18

    A working jQuery validate example:

       $(function () {
            $('input[type=file]').on('change', function() {
                var $el = $(this);
                var files = this.files;
                var image = new Image();
                image.onload = function() {
                    $el
                        .attr('data-upload-width', this.naturalWidth)
                        .attr('data-upload-height', this.naturalHeight);
                }
    
                image.src = URL.createObjectURL(files[0]);
            });
    
            jQuery.validator.unobtrusive.adapters.add('imageminwidth', ['imageminwidth'], function (options) {
                var params = {
                    imageminwidth: options.params.imageminwidth.split(',')
                };
    
                options.rules['imageminwidth'] = params;
                if (options.message) {
                    options.messages['imageminwidth'] = options.message;
                }
            });
    
            jQuery.validator.addMethod("imageminwidth", function (value, element, param) {
                var $el = $(element);
                if(!element.files && element.files[0]) return true;
                return parseInt($el.attr('data-upload-width')) >=  parseInt(param["imageminwidth"][0]);
            });
    
        } (jQuery));
    

提交回复
热议问题