我有文件上传器组件,需要在其中添加尺寸验证器
这是验证器的代码
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 类型。
这里只有图像。
如何获取此文件中图像的宽度和高度?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
使用
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; }); }