我想验证 Nest.js 中文件的 mimetype。但我不能。
@UseInterceptors(FileInterceptor('image'))
@Post('upload_profile_photo')
async uploadProfilePhoto(@UploadedFile() image: UploadImageDto) {
return image;
}
上传图片Dto.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.';
}
}
我的自定义装饰器不执行。有人帮我吗?
您可以定义一个执行验证的函数,并在您希望验证的属性上方的注释中使用它,如下所示:
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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)