2015-01-05 7 views
0

я использую blueimp управления FileUploadblueimp FileUpload - проверить ширину и высоту изображения перед загрузкой

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

я хочу, чтобы убедиться, что если пользователь выбрал изображение менее 700 х 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 х 45) - он показывает мне предупреждение: что минимальный размер изображения требуется 700 х 700

[2], если я снова выберите изображение (800 x800) он показывает мне ошибку снова же - Минимальный размер изображения требуется 700 х 700,

как некоторые его показывает мне более старые значения,

ответ

5

Сегодня я столкнулся с той же проблемой, взял ваш код и немного изменил его. Кажется, что это работает для меня:

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 для fileuploads ...

1

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

      }; 
     }; 
    }); 
}); 
0

Я была такая же проблема, очень хорошо работает, вы можете добавить очередь процесса Значения по умолчанию, добавив настроенный валидатор, который будет применяться к каждому файлу.

$.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(); 
     } 
    } 
}); 
Смежные вопросы