blueimp fileupload - 上传前检查图像的宽度和高度

时间:2015-01-05 14:12:56

标签: javascript jquery html

我使用的是blueimp fileupload控件

http://jsfiddle.net/eLLWN/24/

我想确保如果用户选择的图像少于700 x 700,我不想上传文件并显示警告框

我怎么能这样做?

我正在使用此代码,

$(".photoEditUpload").fileupload({
        url: '/AjaxFileHandler.ashx',
        dataType: 'json',
        cache: false,
        aync: true,
        replaceFileInput: true,
        maxChunkSize: 524288000,
        add: function (e, data) {
            if (this.disabled) return alert('File upload not supported!');
            var F = this.files;
            if (F && F[0]) for (var i = 0; i < F.length; i++) readImage(this, F[i], data);
        },

function readImage($this, file, data) {
    $("#avaryPopup").appendTo("body").modal('show');
    elementVisiablity(true);
    var reader = new FileReader();
    var image = new Image();
    reader.readAsDataURL(file);
    reader.onload = function (_file) {
        image.src = _file.target.result;              // url.createObjectURL(file);
        image.onload = function () {
            var w = this.width,
                h = this.height,
                t = file.type,                           // ext only: // file.type.split('/')[1],
                n = file.name,
                s = ~~(file.size / 1024) + 'KB';
            if (file.size > 524288000) {
                displayAvaryMsg("You have selected too big file, please select a one smaller image file (Max-500MB)", "Alert");
                return;
            }
            var aname = n;
            //alert("your image w is" + w + "and h is" + h + "and size is" + s);
            //if (w < maxSize || h < maxSize) {
            //  displayAvaryMsg('Minimum image dimension required are ' + maxSize + ' x ' + maxSize + ' px', "Alert");
            //  return;
            //}
            //else {
                data.submit();
            //}
        };
        image.onerror = function () {
            displayAvaryMsg("Please select a valid image file (jpg and png are allowed)", "Alert");
        };
    };
}

从上面的代码问题是:

[1]如果我选择图像(45 x 45) - 它会显示警报:所需的最小图像尺寸为700 x 700

[2]如果我再次选择图像(800 x800)它再次显示错误相同 - 所需的最小图像尺寸为700 x 700,

它如何向我展示旧的价值观,

3 个答案:

答案 0 :(得分:7)

我今天遇到了同样的问题,接受了你的代码并对其进行了一些修改。这个似乎对我有用:

jQuery('#fileupload').bind('fileuploadadd', function (e, data) {

    // this will run on all files added - one run per file added! - not 100% sure

    //console.log(e);
    //console.log(data);
    //console.log(data.files);

    // this will remove the element => prevent adding
    //data.files.pop();

    //alert('Adding '+data.files);
    var reader = new FileReader();

    reader.readAsDataURL(data.files[0]);
    reader.data = data;
    reader.file = data.files[0];

    reader.onload = function (_file) {
        console.log(this.data);

        var image = new Image();

        image.src = _file.target.result;              // url.createObjectURL(file);
        image.file = this.file;
        image.data = this.data;
        image.onload = function () {
            console.log(this.data);
            var w = this.width,
                h = this.height,
                n = this.file.name;

                //console.log(this.data);

                /*
                t = _file.type,                           
                n = _file.name,
                s = ~~(_file.size / 1024) + 'KB';
                if (_file.size > 524288000) {
                    alert("You have selected too big file, please select a one smaller image file (Max-500MB)");
                    return;
                }
            var aname = n;*/
            //alert("your image w is " + w + " and h is " + h + " and filename is " + n);
            if ( w < 800 || h < 600 ) {
                //console.log('Too small '+n);
                alert('The following pic is too small: '+n+'! Should be at least 800x600!');
                //reader.data.originalFiles.pop();
                reader.data.files.pop();
                // this is not working, but I don't know why
                //this.data.files.pop();

                //var that = $(this).data('fileupload'),
                //files = that._getFilesFromResponse(data),

                //  displayAvaryMsg('Minimum image dimension required are ' + maxSize + ' x ' + maxSize + ' px', "Alert");
                //  return;
            } else {
                //data.submit();
            }
        };
        image.onerror = function () {
            alert("Please select a valid image file (jpg and png are allowed)");
        };
        // will run later, than the load! => no use
    };

    // will run later, than the image.load! => no use
    /*
    console.log("HE end: "+had_error)
    if ( had_error || true  ) {
        //data.files.error = true;
        //data.abort();
        //return false;
    }*/
});

我留下了一些评论,以便给别人一些线索。我敢肯定,它并不完美,随时可以改变它。

另一方面,更强大的解决方案是使用validate插件进行文件上载......

答案 1 :(得分:1)

我有同样的问题,效果很好,您可以通过添加自定义验证器来附加默认的进程队列,该验证器将应用于每个文件。

$.blueimp.fileupload.prototype.options.processQueue.push({action: 'validateImage'});

// add a customised validator for image width for height, 1920x1080
$.widget('blueimp.fileupload', $.blueimp.fileupload, {
    processActions: {
      validateImage: function(data) {
        var dfd = $.Deferred();
        var file = data.files[data.index];
        if( !/(\.|\/)(gif|jpe?g|png)$/i.test(file.name)){
          dfd.resolveWith(this, [data]);
        }
        else {
          var reader = new FileReader();
          reader.readAsDataURL(file);
          reader.onload = function() {
            var image = new Image();
            image.src = reader.result;
            image.onload = function() {
              if(this.width !== 1920 || this.height !== 1080) {
                data.files.error = true
                file.error = 'Image have to be 1920x1080';
                dfd.rejectWith(this, [data]);
              }
              else {
                dfd.resolveWith(this, [data]);
              }
            }
          };
        }
        return dfd.promise();
      }
    }
});

答案 2 :(得分:0)

V1pr,我已经改进了你的代码,我认为更好的是为特定图像添加验证错误消息而非警报

jQuery('#fileupload').bind('fileuploadadd', function (e, data) {

    var reader = new FileReader();

    data.files.forEach(function (item, index) {
        reader.readAsDataURL(item);
        reader.data = data;
        reader.file = item;
        reader.onload = function (_file) {

            var image = new Image();

            image.src = _file.target.result;
            image.file = this.file;
            image.data = this.data;
            image.onload = function () {
                var w = this.width,
                    h = this.height,
                    n = this.file.name;

                if (w < 800 || h < 600) {
                    data.files.error = true;
                    item.error = "image must be at least 800x600";
                    var error = item.error;
                    $(data.context[index]).find(".error").text(error);
                }

            };
        };
    });
});