代码之家  ›  专栏  ›  技术社区  ›  Dave

如何创建一个NestJS端点,该端点除了一个字符串字段外,还接受两个文件?

  •  1
  • Dave  · 技术社区  · 2 年前

    我正在使用NestJS 10。我想设计一个接受一个字符串字段和两个文件(名为“frontImg”和“backimg”)的端点。我已经创建了此端点

      @Post()
      @UseInterceptors(FileInterceptor('frontImg'), FileInterceptor('backImg'))
      async create(
        @Req() req: Request,
        @Body('title') title: string,
        @UploadedFiles(
          new ParseFilePipe({
            validators: [new FileTypeValidator({ fileType: 'image/jpeg' })],
          }),
        )
        files: { frontImg: Express.Multer.File[]; backImg?: Express.Multer.File[] },
      ) {
        ...
      }
    

    但是当我尝试使用Postman向我的端点提交请求时

    enter image description here

    我从我的NestJS服务器收到了这个400响应。。。

    {
        "message": "Unexpected field",
        "error": "Bad Request",
        "statusCode": 400
    }
    

    设置NestJS端点以接受这两个文件的正确方法是什么?

    1 回复  |  直到 2 年前
        1
  •  0
  •   Jay McDoniel    2 年前

    您将要使用 FileFieldsInterceptor 以处理文件上载到指定字段。所以现在你的控制器看起来是这样的:

     @Post()
      @UseInterceptors(FileFieldsInterceptor([{ name: 'frontImg', maxCount: 1}), { name: 'backImg', maxCount: 1}]))
      async create(
        @Req() req: Request,
        @Body('title') title: string,
        @UploadedFiles(
          new ParseFilePipe({
            validators: [new FileTypeValidator({ fileType: 'image/jpeg' })],
          }),
        )
        files: { frontImg: Express.Multer.File[]; backImg?: Express.Multer.File[] },
      ) {
        ...
      }