I want to validate the mimetype of file at Nest.js. But i can't.
@UseInterceptors(FileInterceptor('image'))
@Post('upload_profile_photo')
async uploadProfilePhoto(@UploadedFile() image: UploadImageDto) {
return image;
}
UploadImageDto.ts
import { IsImageFile } from '../validators/IsImageFile';
export class UploadImageDto {
@Validate(IsImageFile)
mimetype: string;
}
IsImageFile.ts
@ValidatorConstraint({ async: false, name: 'image' })
export class IsImageFile implements ValidatorConstraintInterface {
validate(mimeType: string, args: ValidationArguments) {
// nothing is written on the console
console.log(mimeType);
const acceptMimeTypes = ['image/png', 'image/jpeg'];
const fileType = acceptMimeTypes.find((type) => type === mimeType);
if (!fileType) return false;
return true;
}
defaultMessage(validationArguments?: ValidationArguments): string {
return 'The file type was not accepted.';
}
}
My custom decorator doesn't execute. Anyone help me?
You can define a function which does the validation, and use it in annotation above the property you wish to validate, like so :
import { ValidationOptions, registerDecorator } from 'class-validator';
export function IsImageFile(options?: ValidationOptions) {
return (object, propertyName: string) => {
registerDecorator({
target: object.constructor,
propertyName,
options,
validator: {
validate(mimeType) {
const acceptMimeTypes = ['image/png', 'image/jpeg'];
const fileType = acceptMimeTypes.find((type) => type === mimeType);
return !fileType;
},
},
});
};
}
export class UploadImageDto {
@IsImageFile({message: invalid mime type received})
mimetype: string;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With