Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

chrisgrim's avatar

Getting the width and height from upload value

Hi I am using Jeffrys upload component to upload files.

<template>
    <input type="file" accept="image/*" class="fileinput" @change="onChange">
</template>

<script>
    export default {
        methods: {
            onChange(e) {
                if (! e.target.files.length) return;
                let file = e.target.files[0];
                let reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onload = e => {
                    let src = e.target.result;
                    
                    this.$emit('loaded', {src, file});
                };
            }
        }
    }
</script>

I was hoping to also get the images width and height as well. I've been playing around with adding

var img = new Image();
img.onload = function () {console.log(img.width)}

but I can't seem to get it to send the img width back no matter where I put it in the code.

0 likes
6 replies
aurawindsurfing's avatar

Try:

img.onload = function () {console.log(this.width)}

Hope it helps!

chrisgrim's avatar

Where would that go in the code so it gets returned to my other vue component ?

rodrigo.pedra's avatar
Level 56

The onload event will only fire if you actually set the src property on the Image instance to a valid file/data URL.

Try doing this:

var img = new Image();
img.onload = function () {console.log(img.width)}
img.src = /* data url */

On your code maybe you could do this:

export default {
        methods: {
            onChange(e) {
                if (! e.target.files.length) return;
                let file = e.target.files[0];
                let reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onload = e => {
                    const src = e.target.result;

                    const img = new Image();

                    img.onload = () => {
                        this.$emit('loaded', {src, file, width: img.width});
                    };

                    img.onerror = () => {
                        this.$emit('error');
                    };

                    img.src = src;
                };
            }
        }
    }
chrisgrim's avatar

I see! I had to put it inside both the reader.onload and the img.onload. Thanks so much One question. Why do you have the img.src = src at the very end?

1 like
rodrigo.pedra's avatar

The img.src = src is what will set the image file to the image object and, by consequence, fire those events.

It is placed on the very end so we can attach the event listeners before setting it.

As the image is a data URL there is no delay on loading it, so if we loaded it before setting the event handlers they won't be fired.

chrisgrim's avatar

I see!! Thank you so much for explaining.

1 like

Please or to participate in this conversation.