jeudi 27 avril 2017

Javascript - if boolean true not working

So, i created the following function to check the file uploaded by user is 1) Image only 2) Size less than maxSize KBs 3) Dimensions less than maxWidth and maxHeight

All else is working fine except that the condition where I check dimensions. The value in dimensions is indeed the correct value but the condition if(dimensions) doesn't run even when dimensions=true.

Is there something I am doing wrong?

var maxThumbnailWidth = '1050';
var maxThumbnailHeight = '700';

function imageFileChecks(file, type) // type here refers to either Image or Banner or Thumbnail
{
  var maxSize;
  var maxWidth;
  var maxHeight;
  var dimensions = false;
  if (type == 'image') {
    maxSize = maxImageSize;
    maxWidth = maxImageWidth;
    maxHeight = maxImageHeight;
  }
  if (type == 'banner') {
    maxSize = maxBannerSize;
    maxWidth = maxBannerWidth;
    maxHeight = maxBannerHeight;
  }
  if (type == 'thumbnail') {
    maxSize = maxThumbnailSize;
    maxWidth = maxThumbnailWidth;
    maxHeight = maxThumbnailHeight;
  }

  //First check file type.. Allow only images

  if (file.type.match('image.*')) {
    var size = (file.size / 1024).toFixed(0);
    size = parseInt(size);
    console.log('size is ' + size + ' and max size is ' + maxSize);
    if (size <= maxSize) {

      var img = new Image();
      img.onload = function() {
        var sizes = {
          width: this.width,
          height: this.height
        };
        URL.revokeObjectURL(this.src);

        //console.log('onload sizes', sizes);
        console.log('onload width sizes', sizes.width);
        console.log('onload height sizes', sizes.height);
        var width = parseInt(sizes.width);
        var height = parseInt(sizes.height);
        if (width <= maxWidth && height <= maxHeight) {
          dimensions = true;
          console.log('dimensions = ', dimensions);
        }

      }

      var objectURL = URL.createObjectURL(file);
      img.src = objectURL;

      if (dimensions) {
        alert('here in dimensions true');
        sign_request(file, function(response) {
          upload(file, response.signed_request, response.url, function() {
            imageURL = response.url;
            alert('all went well and image uploaded!');
            return imageURL;
          })
        })
      } else {
        return errorMsg = 'Image dimensions not correct!';
      }


    } else {
      return errorMsg = 'Image size not correct!';
    }

  } else {
    return errorMsg = 'Image Type not correct!';
  }
}

Aucun commentaire:

Enregistrer un commentaire