在Angular 7中验证图像尺寸

时间:2019-06-12 08:59:48

标签: angular typescript

这个问题在JQueryJavaScript上有很多答案。还有Angular的某些版本。

我尝试了很多解决方案,但都没有解决。

我正在使用Angular 7并尝试验证用户上传的图像的WidthHeight

这是我的.html代码段:

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

这是我的.ts组件文件:

  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 个答案:

答案 0 :(得分:1)

尝试这样的事情:


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);
        };
      };
    }
  }
}

关于for:建议您将其更改为类似的内容:

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

更清晰

相关问题