有没有办法使用类验证器实现文件上传的验证?

Dha*_*val 7 validation node.js typescript class-validator

我正在使用类验证器来验证数据,我需要实现文件上传的验证。例如:文件不为空(如果还实现文件必须是图像,那就太好了)。

我尝试通过以下方式:

export class FileModel extends Model {
    @IsNotEmpty()
    file: File

    constructor(body: any) {
        super();
        const {
            file,
        } = body;

        this.file = file;
    }
}
Run Code Online (Sandbox Code Playgroud)

但即使我选择文件,它总是返回“文件不应为空”。有没有办法实现文件上传的验证。

提前致谢 :)

gan*_*alf 8

您可以创建自定义类验证器自定义验证装饰器

interface IsFileOptions {
    mime: ('image/jpg' | 'image/png' | 'image/jpeg')[];
}

export function IsFile(options: IsFileOptions, validationOptions?: ValidationOptions) {
    return function (object: Object, propertyName: string) {
        return registerDecorator({
            name: 'isFile',
            target: object.constructor,
            propertyName: propertyName,
            constraints: [],
            options: validationOptions,
            validator: {
                validate(value: any, args: ValidationArguments) {
                    if (value?.mimetype && (options?.mime ?? []).includes(value?.mimetype)) {
                        return true;
                    }                        
                    return false;
                },
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

前面的自定义装饰器仅检查文件的 mime 类型。您可以编写更复杂的实现,还可以添加文件大小检查等。您可以在 DTO 类中使用像这样的自定义装饰器:

class UploadImageDto{
    @IsFile({ mime: ['image/jpg', 'image/png']})
    file: any;
}
Run Code Online (Sandbox Code Playgroud)

此外,如果您在 NestJs 中使用类验证器,您可以使用nestjs-form-data包含@HasMimeType@IsFile@MaxFileSize更多开箱即用的文件验证装饰器的库。