Function returns the value before Jquery Image load is executed

后端 未结 2 1341
孤独总比滥情好
孤独总比滥情好 2021-01-25 10:29
if (DataService.Validation(file)) {
    //angularjs call to api controller
};    

//DataService
Validation: function (file) {
    var Url =   URL.createObjectURL(file);         


        
2条回答
  •  别那么骄傲
    2021-01-25 11:28

    I had same issue while checking dimension of image as image loading is asynchronous . Also as said by @Abhinandan "IMG load function will execute only after your image is completely loaded by the browser and since its asynchronous your function will not wait for it to execute"

    I used following approach. Hope it will help.

    Set one extra attribute in image tag while on change of file like below

    $('input[type=file]').on('change',function(){
        element = $(this);
        var files = this.files;
        var _URL = window.URL || window.webkitURL;
        var image, file;
        image = new Image();
        image.src = _URL.createObjectURL(files[0]);
            image.onload = function() {
                element.attr('uploadWidth',this.width);
                element.attr('uploadHeigth',this.width);
            }
        });
    

    and now you can modify your function to below

    $.validator.addMethod('checkDim', function (value, element, param) {     
        var image = new Image();
        var file = element.files[0];
        var _URL = window.URL || window.webkitURL;
        image.src = _URL.createObjectURL(file);
            if(element.uploadWidth== param[0] element.uploadHeigth== param[1]){ 
                return true;
            }
            else{            
                return false;
            }
    
    }, 'Image dimension must be as specified');
    

    It work for me

提交回复
热议问题