Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NestJS - Uploading file with dto validation

I`m uploading a file using FileInterseptor, but along with the file I also pass some createDto. The problem is that i validate Dto and if something goes wrong the file is saved anyway. I want the file not to be saved if there are problems with validation. Heres the code:

Controller endpoint:

@UseInterceptors(FileInterceptor('file', saveDocumentToStorage))
  @Post()
  async createDocument(
    @UploadedFile() file: Express.Multer.File,
    @Body() createDocumentDto: CreateDocumentDto,
    @AuthUser() user: UserEntity,
  ): Promise<DocumentDto> {
    const document = await this._documentsService.createDocument(
      file.path,
      createDocumentDto,
      user,
    );
    return document.toDto();
  }

createDto:

export class CreateDocumentDto {
  @IsString()
  @IsNotEmpty()
  readonly name: string;

  @IsString()
  @IsNotEmpty()
  readonly description: string;
}

Thanks for any help

like image 568
Alexander Morozov Avatar asked Oct 27 '25 12:10

Alexander Morozov


1 Answers

I know that my answer is quite late, but maybe it will help someone. In order to validate data in the request using Dto you need to pass ValidationPipe into the @Body like this:

 @UseInterceptors(FileInterceptor('file', saveDocumentToStorage))
  @Post()
  async createDocument(
    @UploadedFile() file: Express.Multer.File,
    @Body(new ValidationPipe()) createDocumentDto: CreateDocumentDto,
    @AuthUser() user: UserEntity,
  ): Promise<DocumentDto> {
    ...
  }

Here's a link to the documentation

like image 69
Viktor Vlasenko Avatar answered Oct 29 '25 01:10

Viktor Vlasenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!