I have file uploader component and need to add size validator in it
This is the code for the 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 the for loop x
parameter has type File
.
Only images here.
How to get the width and height of the image in this file?
P粉2376476452023-09-11 00:14:49
Create an image using Image
and then get the desired dimensions.
You can use file.type
to verify that x
is an image:
Try this:
// 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; }
edit
Get the size simultaneously:
// 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; }); }