1

I am uploading multiple images and before I upload I want to get the width and height of each image. The problem is that my function only returns the width and height of the first image only. Here's my code:

async getWidthAndHeight(files: any) {
    const newPromise = [files].map((file: any, i: any) => {
      return new Promise((resolve, reject) => {
        var reader = new FileReader();
        reader.readAsDataURL(file[i]);
        reader.onload = async (e: any) => {
          var image = new Image();
          image.src = e.target.result;
          image.onload = async () => {
            this.imageWidth = image.width;
            this.imageHeight = image.height;
            this.sizeObj = {
              width: this.imageWidth,
              height: this.imageHeight
            };
            resolve(this.sizeObj)
          }
        }
      })
    })
    const final = await Promise.all(newPromise);
    return final
  }

The return value is an array with the dimensions of the first image alone. I want the function to return the dimensions of all images. Any help would be greatly appreciated. Thanks!

5
  • Is files already an array ? Why are you doing [files].map instead of files.map ? Commented Aug 15, 2022 at 7:53
  • yes files is an array, but for some reason I have to set files to [files] to map the array Commented Aug 15, 2022 at 7:55
  • Can you confirm that the size of your newPromise array is the same as the size of your files array ? Commented Aug 15, 2022 at 7:58
  • The newPromise array always returns only one value regardless of what the size of files array is Commented Aug 15, 2022 at 8:05
  • It means you are not mapping what you are supposed to. Check what is inside files by doing console.log(files) in the beginning of the function Commented Aug 15, 2022 at 8:07

1 Answer 1

2

Considering your files as FileList use this to create array of promises and use file instead of file[i]

const newPromise = Array.from(files).map(file => {
  console.log(file);
  // your code
});
Sign up to request clarification or add additional context in comments.

2 Comments

Good, it works for first file because of line reader.readAsDataURL(file[i]);. So [files] was the culprit.
@Mohid For future problems, be attentive to your data and check if they belong to the type you are expecting. My first question to you was if files was an array and you told me yes when in fact it was FileList.

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.