Hikaru Shindo
Hikaru Shindo

Reputation: 2923

File validator always return error even the file type is correct - NestJS

I'm working on NestJS. I want to upload image files through the API. I added the validator in the API but it is not working. Here is my code,

@Post('upload')
@UseInterceptors(
    FilesInterceptor('files', 3, {
      storage: diskStorage({
        destination: './uploads/',
      }),
    }),
  )
uploadFile(
    @UploadedFiles(
        new ParseFilePipeBuilder()
        .addFileTypeValidator({
            fileType: 'jpg'
        })
        .addFileTypeValidator({
            fileType: 'png'
        })
        .addFileTypeValidator({
            fileType: 'jpeg'
        })
        .addMaxSizeValidator({
          maxSize: 10000
        })
        .build({
            errorHttpStatusCode: HttpStatus.UNPROCESSABLE_ENTITY
        })
    ) files: Array<Express.Multer.File>
) {
  console.log(files);
}

When I test it. I got error like this

enter image description here

Really thanks for every helps.

Upvotes: 0

Views: 435

Answers (3)

Benjamin Drouin
Benjamin Drouin

Reputation: 1

In my code, i have this and his work !

@Roles('ADMIN')
@Post()
@UseInterceptors(FileInterceptor('file'))
create(
  @Body() createExerciseDto: CreateExerciseDto,
  @UploadedFile(
    new ParseFilePipe({
      validators: [
        new MaxFileSizeValidator({ maxSize: 1024 * 1024 * 2 }), // 2MB
        new FileTypeValidator({ fileType: /image\/(jpeg|png|webp|jpg)/ }),
      ],
    }),
  )
  file: Express.Multer.File,
) {

Upvotes: 0

Nivetha
Nivetha

Reputation: 24

try this .addFileTypeValidator({ fileType: /(jpg|jpeg|png)$/, })

Upvotes: -1

Jay McDoniel
Jay McDoniel

Reputation: 70440

The FileTypeValidator is not a "one-of" validator, it's an "exact-match" validator. You'd need to create your own file type validator to be able to check that the file type is one of the provided ones.

Upvotes: 0

Related Questions