Überprüfen Sie die Größe der hochgeladenen Datei
P粉463291248
P粉463291248 2023-09-10 22:52:30
0
1
361

Ich habe eine Datei-Uploader-Komponente und muss darin einen Größenvalidator hinzufügen

Dies ist der Code für den Validator

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

If for-Schleife x 参数具有 File Typ.

Nur Bilder hier.

Wie erhalte ich die Breite und Höhe des Bildes in dieser Datei?

P粉463291248
P粉463291248

Antworte allen(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;
    });
  }
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!