【问题标题】:File field is not being included in @Body decorator in NestJS文件字段未包含在 NestJS 的 @Body 装饰器中
【发布时间】:2021-05-04 17:26:16
【问题描述】:

我正在尝试构建一个简单的路径,用户将在其中发布少量文本数据以及文件。假设一个任务的属性是标题、描述和文件。我为此创建了一个 DTO,如下所示:-

export class CreateTaskDto {
  title: string;
  description: string;
  file: any
}

这里是storage.config.ts

export const storage = diskStorage({
  destination: "./uploads",
  filename: (req, file, callback) => {
    callback(null, generateFilename(file));
  }
});

function generateFilename(file) {
  const filename = file.originalname
  const ext = filename.split(".").pop()
  return `${Date.now()}_${filename}`;
}

tasks.controller.ts

@Post()
@UseInterceptors( FileInterceptor( "file", { storage }))
async createNewTask(@UploadedFile() file, @Body() dto: CreateTaskDto) {
  /*
   here is the dto I received:
   {
      "title": "Task Title",
      "description": "Task Description"
   }

   You can see that the file field is not being added to the dto
   */
}

file 字段数据不包含在 @Body 装饰器变量 dto 中。我知道我可以通过file 变量访问文件数据,但是有没有办法指示nest 将文件值包含到@Body 装饰器中?

谢谢

【问题讨论】:

    标签: node.js typescript nestjs


    【解决方案1】:

    这就是multer 的工作原理,它获取上传的文件并将它们附加到req.filereq.files,具体取决于发送的是一个还是多个。如果需要,您可以创建一个 custom decoratorreq.bodyreq.file 合并在一起,但通常这不是 Nest 所做的,而是底层包本身。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-09
      • 2021-09-30
      • 1970-01-01
      • 2021-11-25
      • 2021-12-30
      • 2018-07-27
      • 2020-06-30
      • 2012-11-12
      相关资源
      最近更新 更多