0

I have a code in Vuejs that it uploads a image but I need to check the width and height of that image I have my code like this:

This is my input :

<input ref="file" accept="image/png" type="file" class="form-control" v-on:change="onFileChange" required>

This is a method that I use to upload when select the image :

onFileChange(e){
  this.file = e.target.files[0];
  this.noFile = e.target.files.length;
},

This is my code to upload :

onSubmit(e) {
   this.loading = true; //the loading begin
   e.preventDefault();
   let currentObj = this;

   const config = {
      headers: { 'content-type': 'multipart/form-data' }
   }

   axios.post('/api/section/store?api_token='+App.apiToken, formData, config)
       .then(function (response) {
       currentObj.success = response.data.success;
    })
    .catch(function (error) {
       console.log(error);
    })

   formData.append('file', this.file);
}

So I wonder how can I retrieve the width and height? I have tried this:

onFileChange(e){
  this.file = e.target.files[0];
  console.log(this.file.width);
  this.noFile = e.target.files.length;
},

It says undefined, so how can I do that ?

1 Answer 1

1

A File object doesn't have a width and height. You would need to create an image object.

async onFileChange(e) {
   this.file = e.target.files[0];
   this.noFile = e.target.files.length;
   const photoUrl = URL.createObjectURL(this.file);
   const image = new Image();
   const imageDimensions = await new Promise((resolve) => {
      image.onload = () => {
        const dimensions = {
          height: image.height,
          width: image.width,
        };
        resolve(dimensions);
      };
     image.src = photoUrl;
    });
    console.log(imageDimensions);
}
Sign up to request clarification or add additional context in comments.

2 Comments

It says Uncaught (in promise) TypeError: URL.createObjectUrl is not a function what could it be ?
URL.createObjectUrl is a default method as described here: developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL. I accidentally typed createObjectUrl instead of createObjectURL. See the edit for the correct code.

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.