[英]Creating custom validator for image uploading at Nest.js with class-validator package
I want to validate the mimetype of file at Nest.js.我想在 Nest.js 验证文件的 mimetype。 But i can't.但我不能。
@UseInterceptors(FileInterceptor('image')) @Post('upload_profile_photo') async uploadProfilePhoto(@UploadedFile() image: UploadImageDto) { return image; }
UploadImageDto.ts UploadImageDto.ts
import { IsImageFile } from '../validators/IsImageFile'; export class UploadImageDto { @Validate(IsImageFile) mimetype: string; }
IsImageFile.ts是图像文件.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;
}
You can use in-built file validator您可以使用内置的文件验证器
@UploadedFile(
new ParseFilePipe({
validators: [
new FileTypeValidator({fileType: /\.(jpg|jpeg|png)$/}),
],
})
)
Note: File type is RegExp
.注意:文件类型为RegExp
。
See: https://docs.nestjs.com/techniques/file-upload#validators请参阅: https://docs.nestjs.com/techniques/file-upload#validators
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.