檢查上傳文件的尺寸
P粉463291248
P粉463291248 2023-09-10 22:52:30
0
1
360

我有文件上傳器元件,需要在其中加入尺寸驗證器

這是驗證器的程式碼

export const filesDimensionValidator =
  (maxWidth: number, maxHeight: number): ValidatorFn =>
  (control: AbstractControl): ValidationErrors | null => {
    const value: IUploadFileControl = control.value;

    if (value == null) {
      return null;
    }

    for (const x of value.allFiles) {
      if (x.size > maxFileSize) {
        return { file_max_size: VALIDATION_LABEL_ATTACHMENT_MAX_SIZE };
      }
    }

    return null;
  };

如果 for 迴圈 x 參數具有 File 類型。

這裡只有圖像。

如何取得此文件中圖像的寬度和高度?

P粉463291248
P粉463291248

全部回覆(1)
P粉237647645

使用Image建立影像,然後取得所需的尺寸。

您可以使用file.type來驗證x是否是映像:

試試這個:

// add mime type check
if (x?.type.includes('image/')) {
  
  const url = URL.createObjectURL(x);
  const img = new Image();

  img.onload = function () {
    console.log(img.width, img.height);
    URL.revokeObjectURL(img.src);
  };

  img.src = url;

}

編輯

同步取得尺寸:

// pass file to the method and hold execution
console.log(await this.getDimensions(x));

// method that gets and return dimensions from a file
  getDimensions(x: File) : Promise<{width:number, height:number}> {
    return new Promise((resolve, reject) => {
      const url = URL.createObjectURL(x);
      const img = new Image();
      img.onload = () => {
        URL.revokeObjectURL(img.src);
        resolve({ width: img.width, height: img.height });
      };
      img.src = url;
    });
  }
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!