0

I have two jQuery functions for image upload and saved in to the path as well a check of image upload size and height and width. Both functions work fine, but not in a synchronous way. It jumps out on next function without getting the result of other one.

Whenever I upload an image, the "checkheightwidth" function will always return false.
What's gong wrong?

var _URL = window.URL || window.webkitURL;

$("#UploadImg").change(function(e) {
  if (checkFileDetails()) {
    var data = new FormData();
    var files = $("#UploadImg").get(0).files;
    if (files.length > 0) {
      data.append("MyImages", files[0]);
    }


    $.ajax({
      url: "/Image/UploadFile",
      type: "POST",
      processData: false,
      contentType: false,
      data: data,
      async: false,
      success: function(response) {
        //code after success
        $("#txtImg").val('/Upload/' + response);
        $("#imgPreview").attr('src', '/Upload/' + response);
      },
      error: function(er) {
        alert(er);
      }

    });
  } else {
    //alert('something went wrong');
    console.log('ss');
  }

});

function checkFileDetails() {


  var fi = document.getElementById('UploadImg');
  if (fi.files.length > 0) { // FIRST CHECK IF ANY FILE IS SELECTED.
    for (var i = 0; i <= fi.files.length - 1; i++) {
      var fileName, fileExtension, fileSize, fileType, dateModified;

      // FILE NAME AND EXTENSION.
      fileName = fi.files.item(i).name;
      fileExtension = fileName.replace(/^.*\./, '');

      // CHECK IF ITS AN IMAGE FILE.
      // TO GET THE IMAGE WIDTH AND HEIGHT, WE'LL USE fileReader().
      if (fileExtension == 'png' || fileExtension == 'jpg' || fileExtension == 'jpeg') {
        // readImageFile(fi.files.item(i));             // GET IMAGE INFO USING fileReader().
        var defer = $.Deferred();
        if (checkheightwidth(fi.files.item(i))) // GET IMAGE INFO USING other option().
        {

          return true
        } else {
          return false;
        }
      } else {

        alert('Please upload image file..!!');
        $('#UploadImg').val('');
        return false;
        // IF THE FILE IS NOT AN IMAGE.

        //fileSize = fi.files.item(i).size;  // FILE SIZE.
        //fileType = fi.files.item(i).type;  // FILE TYPE.
        //dateModified = fi.files.item(i).lastModifiedDate;  // FILE LAST MODIFIED.

        //document.getElementById('fileInfo').innerHTML =
        //    document.getElementById('fileInfo').innerHTML + '<br /> ' +
        //    'Name: <b>' + fileName + '</b> <br />' +
        //    'File Extension: <b>' + fileExtension + '</b> <br />' +
        //    'Size: <b>' + Math.round((fileSize / 1024)) + '</b> KB <br />' +
        //    'Type: <b>' + fileType + '</b> <br />' +
        //    'Last Modified: <b>' + dateModified + '</b> <br />';
      }

    }

    // GET THE IMAGE WIDTH AND HEIGHT USING fileReader() API.

  }
}


function checkheightwidth(imgfile) {
  var file, img;
  if ((file = imgfile)) {
    img = new Image();
    img.onload = function() {
      alert(this.width + " " + this.height);
      var w = this.width;
      var h = this.height;

      if (w < 1024 && h < 790) {

        alert('Please upload high resolution image.');
        $('#UploadImg').val('');
        return false;

      } else {
        return true;
      }
    };
    img.src = _URL.createObjectURL(file);
    //return true;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="file" id="UploadImg" />
<br />
<p id="fileInfo"></p>
<img id="imgPreview" class="thumbnail" style="height:200px; width:200px" />
<div class="input-group">
  <span class="input-group-btn">
        <button class="btn" type="button" data-clipboard-target="#txtImg" onclick="copytxt();">
            <i class="fa fa-clipboard" aria-hidden="true"></i>
        </button>
    </span>
  <input type="text" placeholder="Copy Image link" id="txtImg" class="form-control" aria-label="..." onchange="copytxt();" />

</div>
showdev
  • 28,454
  • 37
  • 55
  • 73
mitesh
  • 23
  • 9
  • 1
    Use `async:false` is evil, mmmkay: https://stackoverflow.com/a/41756658/2181514 – freedomn-m Mar 22 '19 at 06:46
  • The problem with your code is `checkheightwidth` function doesn't return anything as you have commented `//return true;`. So it will return `undefined`. That's why you're getting `false` in `if condition`. – Karan Mar 22 '19 at 06:46
  • Hi Karan, Thanks for answer , but if I uncomment return true so in any of the case it will true which is not workable also. I have to restrict image of lower resolution – mitesh Mar 22 '19 at 06:55
  • You can check my answer. Hopefully it will work for you. – Karan Mar 22 '19 at 06:59
  • Sure Karan, I will check this and thank you for your help – mitesh Mar 22 '19 at 07:09
  • Thank you Karan It is working now .. – mitesh Mar 22 '19 at 07:35

1 Answers1

0

You have to move your code upload file code to some another function like uploadFile below. And then call this function from img.onload before return true.

Also as per comment from @freedomn-m you should not use async:false. Even from your code I can see that if you remove async:false then also it will not make any issue.

var _URL = window.URL || window.webkitURL;

$("#UploadImg").change(function(e) {
  if (checkFileDetails()) {} else {
    //alert('something went wrong');
    console.log('ss');
  }

});

function uploadFile() {
  var data = new FormData();
  var files = $("#UploadImg").get(0).files;
  if (files.length > 0) {
    data.append("MyImages", files[0]);
  }

  $.ajax({
    url: "/Image/UploadFile",
    type: "POST",
    processData: false,
    contentType: false,
    data: data,
    async: false,
    success: function(response) {
      //code after success
      $("#txtImg").val('/Upload/' + response);
      $("#imgPreview").attr('src', '/Upload/' + response);
    },
    error: function(er) {
      alert(er);
    }

  });

}

function checkFileDetails() {

  var fi = document.getElementById('UploadImg');
  if (fi.files.length > 0) { // FIRST CHECK IF ANY FILE IS SELECTED.
    for (var i = 0; i <= fi.files.length - 1; i++) {
      var fileName, fileExtension, fileSize, fileType, dateModified;

      // FILE NAME AND EXTENSION.
      fileName = fi.files.item(i).name;
      fileExtension = fileName.replace(/^.*\./, '');

      // CHECK IF ITS AN IMAGE FILE.
      // TO GET THE IMAGE WIDTH AND HEIGHT, WE'LL USE fileReader().
      if (fileExtension == 'png' || fileExtension == 'jpg' || fileExtension == 'jpeg') {
        // readImageFile(fi.files.item(i));             // GET IMAGE INFO USING fileReader().
        var defer = $.Deferred();
        if (checkheightwidth(fi.files.item(i))) // GET IMAGE INFO USING other option().
        {

          return true
        } else {
          return false;
        }
      } else {

        alert('Please upload image file..!!');
        $('#UploadImg').val('');
        return false;
        // IF THE FILE IS NOT AN IMAGE.

        //fileSize = fi.files.item(i).size;  // FILE SIZE.
        //fileType = fi.files.item(i).type;  // FILE TYPE.
        //dateModified = fi.files.item(i).lastModifiedDate;  // FILE LAST MODIFIED.

        //document.getElementById('fileInfo').innerHTML =
        //    document.getElementById('fileInfo').innerHTML + '<br /> ' +
        //    'Name: <b>' + fileName + '</b> <br />' +
        //    'File Extension: <b>' + fileExtension + '</b> <br />' +
        //    'Size: <b>' + Math.round((fileSize / 1024)) + '</b> KB <br />' +
        //    'Type: <b>' + fileType + '</b> <br />' +
        //    'Last Modified: <b>' + dateModified + '</b> <br />';
      }

    }

    // GET THE IMAGE WIDTH AND HEIGHT USING fileReader() API.

  }
}


function checkheightwidth(imgfile) {
  var file, img;
  if ((file = imgfile)) {
    img = new Image();
    img.onload = function() {
      alert(this.width + " " + this.height);
      var w = this.width;
      var h = this.height;

      if (w < 1024 && h < 790) {

        alert('Please upload high resolution image.');
        $('#UploadImg').val('');
        return false;

      } else {
        uploadFile();
        return true;
      }
    };
    img.src = _URL.createObjectURL(file);
    //return true;
  }
}
Karan
  • 12,059
  • 3
  • 24
  • 40