#File Upload and Serialized data

1 messages · Page 1 of 1 (latest)

gentle nebula
#

I have a register controller that also includes a file upload however the body of the request is always unserialized. I do not know how to resolve this.

  @Post('register')
  @UseInterceptors(
    FileInterceptor('profile_picture', {
      storage: diskStorage({
        destination: './uploads',
        filename: (req, file, callback) => {
          const ext = extname(file.originalname);
          const filename = `${req.session.username}-${Date.now()}${ext}`;
          callback(null, filename);
        }
      })
    })
  )
  async register(
    @Body() body: CreateUserDto,
    @Req() req: Request,
    @UploadedFile() profile_picture?: Express.Multer.File
  ) {
    return await this.authService.register(body, req, profile_picture);
  }

I tried to do JSON.parse(body) but kept getting the error TypeError: Cannot convert object to primitive value. I'm not sure if I want to split this into separate controllers for uploading the file and creating the user.

visual urchin
#

Without the parse, what does your body look like?

marble light
#

As far as I know, when submitting multi part form data, everything is sent as either key-value pairs. The value could be either a string or some binary data representing a file. You cant really send a json payload like regular requests. I'd suggest keeping them separate

#

but I might be wrong. Please correct me guys @here

gentle nebula
visual urchin
#

And what does it look like in the client before it is sent?

gentle nebula
#

This is what the payload is:

  {
    "first_name": "xxxx",
    "last_name": "xxx",
    "email": "[email protected]",
    "username": "xxx3",
    "password": "xxxxxxxxxxxxxxxxxxx",
    "date_of_birth": 1111111111,
    "occupation": "xxx",
    "gender": "xxx",
    "address": {
        "line_1": "xxx",
        "line_2": null,
        "city": "xxx",
        "state": "xxx",
        "country": "xxx"
    }
}

and this is what the body looks like:

{
  body: [Object: null prototype] {
    body: '{\n' +
      '\t"first_name": "xxx",\n' +
      '\t"last_name": "xxx",\n' +
      '\t"email": "[email protected]",\n' +
      '\t"username": "xxx",\n' +
      '\t"password": "xxxxxxxxxxxxxxxxxxx",\n' +
      '\t"date_of_birth": 1111111111,\n' +
      '\t"occupation": "xxx",\n' +
      '\t"gender": "xxx",\n' +
      '\t"address": {\n' +
      '\t\t"line_1": "xxx",\n' +
      '\t\t"line_2": null,\n' +
      '\t\t"city": "xxx",\n' +
      '\t\t"state": "xxx",\n' +
      '\t\t"country": "xxx"\n' +
      '\t}\n' +
      '}'
  }
}
visual urchin
#

How do you add this payload to the request?

gentle nebula
gentle nebula
visual urchin
# gentle nebula

Right, so instead of adding body as a JSON string it should definitely be each key value. If you really want to do body like this you need to do JSON.parse(body.body)

gentle nebula