How to get the width and height of a picture when uploading a picture?

Why do you get 0 most of the time when you write like this? only individual pictures can output width. why?

var upload = document.getElementById("upload");
upload.onchange=function(){
        var file = this.files[0];
        if (file) {
                var reader = new FileReader();
                reader.onload = function (event) {
                    var txt = event.target.result;
                    var img = document.createElement("img");
                    img.src = txt;
                    console.log(img.width);
                    document.getElementById("result").appendChild(img);
                };
            }
            reader.readAsDataURL(file);
}
Nov.15,2021

var upload = document.getElementById('upload');
upload.onchange=function(){
        var file = this.files[0];
        if (file) {
                var reader = new FileReader();
                reader.onload = function (event) {
                    var txt = event.target.result;
                    var img = document.createElement("img");
                    img.src = txt;
                    
                    img.onload = function () {
                        console.log(img.width);
                        document.getElementById("result").appendChild(img);
                    }
                    
                    
                };
            }
            reader.readAsDataURL(file);
}
Menu