Why is the ParseFilePipe validation not working as intended in my nestjs api route?

33 Views Asked by At

First Problem (Max File Size) I've set the max file size 2MB but I still get error even when I uploaded an image that is few kbs in size. The code:

  @Patch()
  @UseGuards(AuthGuard)
  @UseInterceptors(
    FileFieldsInterceptor([
      { name: 'avatar', maxCount: 1 },
      { name: 'cover', maxCount: 1 },
    ])
  )
  async update(
    @Request() req,
    @Body(new ValidationPipe({ transform: true, whitelist: true }))
    updateProfileDto: UpdateProfileDto,
    @UploadedFiles(
      new ParseFilePipe({
        fileIsRequired: false,
        validators: [
          new MaxFileSizeValidator({
            maxSize: 2 * 1024 * 1024,
            message: 'File is too large. Max size is 2MB',
          }),
        ],
        errorHttpStatusCode: HttpStatus.UNPROCESSABLE_ENTITY,
      })
    )
    files
  ) {
    console.log('files', files);
  }

PATCH Request Using Postman. URL: http://localhost:5984/api/profile Attached image in form-data tab.

The Response I get:

{
    "path": "/api/profile",
    "statusCode": 422,
    "message": [
        "File is too large. Max size is 2MB"
    ],
    "success": false
}

Second Problem (File Type Validation)

When uploading a .png image.

{
    "path": "/api/profile",
    "statusCode": 422,
    "message": [
        "Validation failed (expected type is .(png|jpeg|jpg))"
    ],
    "success": false
}

I tried using ParseFilePipeBuilder instead of ParseFilePipe, but no difference. For file type validation, I tried setting the fileType as image/png, png, .png etc. Please let me know if I missed to attach any other information in this post.

0

There are 0 best solutions below