NestJS 中的 FileInterceptor 和 Body Issue(在请求中上传文件和数据)

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

我有以下控制器:

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');
    }
  }

我需要上传文件并在同一个查询中提供一些数据。

因为要上传文件,所以我这样设置Postman:

第一个问题:我如何发送文件以及数据图片 n°1 ?

我在另一个工具中搜索了 API 个请求,我找到了 Postwoman

这是我使用的配置:

但响应总是一样的:它没有检测到数据。 (即 { name: foo, color: bar}

第二个问题:我该如何解决这个问题?是否可以将数据放在文件中?如果可能的话,我怎样才能在 NestJS 中实现它?

非常感谢您阅读我的问题 :) 如有任何帮助,我们将不胜感激。

你很接近。要在 Postman 的单个请求中上传文件和额外属性,您需要选择form-datax-www-form-urlencoded .

这是一个简单的 NestJS 控制器,显示您可以获得所有数据:

import { Body, Controller, Post, UploadedFile, UseInterceptors } from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';

@Controller('upload-stack-overflow')
export class UploadWhosebugController {

  @Post('upload')
  @UseInterceptors(FileInterceptor('file'))
  uploadSingleFileWithPost(@UploadedFile() file, @Body() body) {
    console.log(file);
    console.log(body.firstName);
    console.log(body.favoriteColor);
  }
}