Search code examples
postmannestjsnestjs-swagger

FileInterceptor and Body Issue in NestJS (upload a file and data in a request)


I have the following controller :

createCollection(
    @UploadedFile() file,
    @Body() createCollectionDto: CreateCollectionDto,
    @GetUser() user: User,
  ): Promise<Collection> {
    this.logger.verbose(
      `User "${
        user.username
      }" creating a new collection. Data: ${JSON.stringify(
        createCollectionDto,
      )} of "${user.username}"`,
    );
    if (file) {
      return this.collectionService.createCollection(
        createCollectionDto,
        user,
        file,
      );
    } else {
      throw new InternalServerErrorException('File needed');
    }
  }

I need to upload a file and In the same query give some data. data I want to give to the api

Because I want to upload a file, I set up Postman like this: second setup of postman

First Question : How can I send the file along with the data showed in picture n°1 ?

I searched another tool for API requests and I found Postwoman

Here is the config I used : Postwoman config

But the response is always the same: It doesn't detects the data. (i.e. { name: foo, color: bar} )

enter image description here

Second Question : How can I solve this issue ? Is it possible to put data along a file ? If it is possible how can I achieve that in NestJS ?

Thank you very much for reading my question :) Any help would be appreciated.


Solution

  • You're pretty close. To upload a file and extra properties in a single request in Postman, you need to choose form-data and not x-www-form-urlencoded.

    Screenshot of Postman

    And here is a simple NestJS controller that shows that you can get all of the data:

    import { Body, Controller, Post, UploadedFile, UseInterceptors } from '@nestjs/common';
    import { FileInterceptor } from '@nestjs/platform-express';
    
    @Controller('upload-stack-overflow')
    export class UploadStackOverflowController {
    
      @Post('upload')
      @UseInterceptors(FileInterceptor('file'))
      uploadSingleFileWithPost(@UploadedFile() file, @Body() body) {
        console.log(file);
        console.log(body.firstName);
        console.log(body.favoriteColor);
      }
    }