#Help Intercepting Multiple Files and Body in Upload

5 messages · Page 1 of 1 (latest)

oblique sonnet
#

I'm having trouble uploading a couple of files alongside a body to a Nest JS endpoint. I've got a React client app sending multipart/form-data to a NestJS endpoint.

I can confirm that the form data being sent from the client using axios looks as follows

formData: FormData {
  name: 'test name',
  shortName: 'short test name',
  ... other body fields,
  smallImage: [object File],
  largeImage: [object File],
}

Here is the Nest JS endpoint

@Post('create')
  @UseInterceptors(
    FileFieldsInterceptor([
      { name: 'smallImage', maxCount: 1 },
      { name: 'largeImage', maxCount: 1 }
    ])
  )
  @UseGuards(JwtAuthGuard)
  @Roles(Role.SysAdmin)
  async create(
    @Body() createOrganizationDto: CreateOrganizationDto,
    @UploadedFiles() files: { smallImage?: Express.Multer.File; largeImage?: Express.Multer.File }
  ) {
    console.log('files: ', files.smallImage)
    let smallImageKey = ''
    let largeImageKey = ''

    if (files.smallImage) {
      smallImageKey = await this.organizationsService.saveImage('sm', files.smallImage)
    }
    if (files.largeImage) {
      largeImageKey = await this.organizationsService.saveImage('lg', files.largeImage)
    }
    return this.organizationsService.create(createOrganizationDto)
  }

The problem I'm having is that the logs show the files as undefined, but if I log the body I see all of the form data as well as the two images as [object File]

pine elm
#

In client it should be

const formData = new FormData();
formData.append('name', 'test name');
formData.append('shortName', 'short test name');
formData.append('smallImage', smallImageFile); // Key matches the NestJS interceptor
formData.append('largeImage', largeImageFile); // Key matches the NestJS interceptor

axios.post('/api/create', formData, {
  headers: {
    'Content-Type': 'multipart/form-data',
    Authorization: `Bearer ${token}` // Include JWT if required
  }
});

Try this and tell if solve the problem.

#

Some references to you look