3

This question have lots of answers on JQuery and JavaScript. And also some versions of Angular.

I tried lots of solutions but none of them work out.

I'm using Angular 7 and trying to validate the Width and Height of the Image Uploaded by the user.

Here's my .html code snippet:

<input type="file" name="upload" id="androidPhoneFile" class="upload-box" placeholder="Upload File" multiple="multiple" (change)="onAndroidPhoneChange($event)" formControlName="androidPhone" #androidPhonePhoto>

And here's my .ts component file:

AddFilesToFormData(event: any, fileName: string) {
const reader = new FileReader();
const img = new Image();
img.onload = function() {
  const height = img.height;
  const width = img.width;
  console.log('Width and Height', width, height);
};

img.src = event.target.files[0];
if (event.target.files && event.target.files.length) {
  const [file] = event.target.files;
  reader.readAsDataURL(file);
  reader.onload = () => {
    for (let i = 0; i < event.target.files.length; i++) {
      this.formData.append(fileName, event.target.files[i]);
      this.numberOfPhotos++;
    }
  };
}}

1 Answer 1

11

Try something like this:


AddFilesToFormData(event: any, fileName: string) {
  if (event.target.files && event.target.files.length) {
    for (const file of event.target.files) {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => {
        const img = new Image();
        img.src = reader.result as string;
        img.onload = () => {
          const height = img.naturalHeight;
          const width = img.naturalWidth;
          console.log('Width and Height', width, height);
        };
      };
    }
  }
}

About the for: I recommend you to change it for something like that:

    for (const image of event.target.files) {
      this.formData.append(fileName, image);
      this.numberOfPhotos++;
    }

It's clearer.

Sign up to request clarification or add additional context in comments.

3 Comments

What if I uploaded more than one image ?? In this case I will see the Width and Height of the Last Selected Image.
Since you used img.src = event.target.files[0]; I thought you were uploading a single image. If you are uploading more than 1, you just need to play a bit with the code. I'll try now to modify it
I added a for but I couldn't test it (the previous code was tested indeed for one single image). I guess it will work. If it does not, you just need to manipulate it a bit or let me know it and I'll fix it

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.