0

i have a input file which is used to upload images. However, I have to validate its size before upload. As below is the code I've tried on.

I have a parent function, that calls the method,ValidateImageSize( ):

$('input:file').change(function (e) {

            if (ValidateImageSize(this))
                // do something
            else
                alert("wrong size");

        });

and the method shown as below:

    var ValidateImageSize = function (input) {

       var reader = new FileReader();
       reader.onload = function (e) {

           var img = new Image();
           img.onload = function (e) {
              return this.height == 40 && this.width == 40 ? true : false;
           }
           img.src = e.target.result;
       }
       reader.readAsDataURL(input.files[0]);
   };

The method ValidateImageSize() always returns 'undefined' to its parents, cause it have yet executes the onload functions.

The output I need is either true/ false. Perhaps the structure of my codes itself is incorrect.

How can I solve this?

0

1 Answer 1

3

Use callback, something like as below:

var validation_callback = function(isValid) {
    if (isValid) {
        // do something
    } else {
        alert("wrong size");
    }
};

$('input:file').change(function(e) {
    ValidateImageSize(this, validation_callback);
});

var ValidateImageSize = function (input, callback) {
    var reader = new FileReader();
    reader.onload = function (e) {
        var img = new Image();
        img.onload = function (e) {
           var isValid = this.height == 40 && this.width == 40 ? true : false;
           callback(isValid);
        };
        img.src = e.target.result;
    };
    reader.readAsDataURL(input.files[0]);
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.