Search code examples
nestjsswagger

how to send in swagger multer file with body combined


i have a nest js project with an endpoint that accepts files with body. it works with postman, but when i add swagger @ApiParam , it doesnt send the files to the field

my endpoint:

@ApiParam({ name: 'body', type: SendMessageParamsBody, description: 'body params ...' })
    @ApiParam({ name: 'attachments', type: 'file', description: 'file attachments' })
    @ApiOperation({ summary: 'send email' })
    @ApiResponse({ status: 200, description: 'sends email - main end point ' })
    @Post('send-email')
    @UseGuards(ThrottlerGuard)
    @UseInterceptors(FileFieldsInterceptor([
        {name: 'attachments', maxCount: 4}, //must be same as the field name
    ]))
    async sendEmail(@Body() body: SendMessageParamsBody,
                    @UploadedFiles() attachments: {attachment: Express.Multer.File[]},   //undefined when not passed
    ): Promise<MyApiResponse> {
        return await this.notificationService.handleSendMessageRequest(body, attachments?.attachments, MediumType.EMAIL)
    }

i dont receive any files.

tried to add as abdul suggested

@ApiBody({
schema: {
  type: 'object',
  properties: {
    attachments: {
      type: 'string',
      format: 'binary',
    },
  },
},
})

but the attachments were still undefined when passed something in the attachments field enter image description here

also m id like it to be a file chooser.

any idea how to make the swagger pass files to the 'attachments' field which chooser? thnx


Solution

  • the issue was 2 things:

    1. i used fileFieldsInterceptor but you need to use: @UseInterceptors(FilesInterceptor('attachments'))

    2. you need to add the file into the dto of the controller to enable swagger render it as file chooser.,

    @Post('upload')
    @ApiConsumes('multipart/form-data')
    @UseInterceptors(FilesInterceptor('files'))
    upload(
      @Body() dto: SampleDto,
      @UploadedFiles() files: Express.Multer.File[],
    ) {
      return {
        dto,
        files: files?.map((f) => f.buffer.toString()),
      };
    }
    
    export default class SampleDto {
      @IsOptional()
      @ApiProperty({
        type: 'string',
        required: false,
        title: 'fields',
        description: 'fields to aggregate',
      })
      field: string;
    
      @ApiProperty({
        type: 'file',
        name: 'files',
        format: 'binary',
      })
      files: Express.Multer.File[];
    }