Search code examples
typescriptpostfile-uploadnestjsmultipartform-data

Nestjs: empty body when post multipart/form-data with DTO and whitelist = true


I create an POST with multipart/form-data.

@UseInterceptors(FileInterceptor('file'))
@Post('upload')
@ApiConsumes('multipart/form-data')
uploadFile(@Body() body: FileDto, @UploadedFile() file: Express.Multer.File) {
  console.log('body: ', body)

  return 'uploaded'
}

FileDto:

export class FileDto {
  @ApiProperty()
  name: string

  @ApiProperty({ type: 'string', format: 'binary' })
  file: any
}

The console.log

When whitelist: true: body: {}.

When whitelist: false: body: { name: 'some name' }

Swagger: enter image description here

And pipe validation with class-validator seem not work with multipart/form-data

How can I fix that?


Solution

  • With whitelist: true, class-validator strips unknown values from the payload. As your FileDto has no class-validator decorators, the name is properly stripped. Either add @Allow() or a class-valdiator validation decorator to keep the property.