網站搜尋

typescript - 在 Angular 7 中驗證圖片尺寸


這個問題在 JQuery 和 JavaScript 上有很多答案。也有一些 Angular 的版本。

我嘗試了很多解決方法,但沒有一個有效。

我正在使用 Angular 7,並嘗試驗證用戶上傳的圖片的 寬度 和 高度。

這是我的 .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

試試像這樣的東西:

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

更清楚了。