首頁  >  問答  >  主體

檢查上傳文件的尺寸

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

這是驗證器的程式碼

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粉463291248P粉463291248405 天前363

全部回覆(1)我來回復

  • P粉237647645

    P粉2376476452023-09-11 00:14:49

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

    回覆
    0
  • 取消回覆