首页  >  问答  >  正文

检查上传文件的尺寸

我有文件上传器组件,需要在其中添加尺寸验证器

这是验证器的代码

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 天前364

全部回复(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
  • 取消回复