Search code examples
file-uploadnestjsmultipartform-datamulter

How do I create a NestJS endpoint that accepts exactly two files in addition to a string field?


Im' using NestJS 10. I would like to design an endpoint that accepts one string field and two files (named "frontImg" and "backimg"). I have created this endpoint

  @Post()
  @UseInterceptors(FileInterceptor('frontImg'), FileInterceptor('backImg'))
  async create(
    @Req() req: Request,
    @Body('title') title: string,
    @UploadedFiles(
      new ParseFilePipe({
        validators: [new FileTypeValidator({ fileType: 'image/jpeg' })],
      }),
    )
    files: { frontImg: Express.Multer.File[]; backImg?: Express.Multer.File[] },
  ) {
    ...
  }

but when I attempt to submit a request to my endpoint using Postman

enter image description here

I get this 400 response from my NestJS server ...

{
    "message": "Unexpected field",
    "error": "Bad Request",
    "statusCode": 400
}

What's the proper way to set up my NestJS endpoint to accept these two files?


Solution

  • You'll want to use the FileFieldsInterceptor to handle file uploads to specified fields. So now your controller would look like this:

     @Post()
      @UseInterceptors(FileFieldsInterceptor([{ name: 'frontImg', maxCount: 1}), { name: 'backImg', maxCount: 1}]))
      async create(
        @Req() req: Request,
        @Body('title') title: string,
        @UploadedFiles(
          new ParseFilePipe({
            validators: [new FileTypeValidator({ fileType: 'image/jpeg' })],
          }),
        )
        files: { frontImg: Express.Multer.File[]; backImg?: Express.Multer.File[] },
      ) {
        ...
      }