【问题标题】:Nestjs Uploading a file using @UploadedFile decorator : how to make the parameter non-mandatory?Nestjs 使用@UploadedFile 装饰器上传文件:如何使参数成为非强制性参数?
【发布时间】:2023-01-02 00:10:41
【问题描述】:

使用 Nest.js,我正在尝试为我的膳食计划应用程序中的一种成分编写一条创建(发布)路线。该路由将作为请求主体接收描述(可选)和名称(强制)以及可选图像。我使用 Objection.js 作为 ORM。

我阅读了文件上传Nest.js File Upload handling with Multer 的 Nest.js 文档,并尝试按照与文档中相同的方式进行操作。问题是,我无法在任何地方找到如何在使文件可选的同时使用 UploadedFile 装饰器。当我尝试通过 Postman 创建没有图像的新成分时,我收到以下错误消息:

{
    "statusCode": 400,
    "message": "File is required",
    "error": "Bad Request"
}

有人在这里偶然发现了这个问题并找到了使参数可选的解决方案吗?我知道我可以创建一个 Patch 路由来修改成分并在之后向其添加图像作为解决方法,但我想知道在保持实际情况的同时我是否可以做任何事情。

这是我的控制器的代码:

@Post()
  @UseInterceptors(
    FileInterceptor('image', {
      storage: diskStorage({
        destination: './assets/images/ingredient',
        filename: getUniqueFileName,
      }),
    }),
  )
  @UseFilters(DeleteFileOnErrorFilter)
  async create(
    @Body() dto: CreateIngredientDto,
    @UploadedFile(
      new ParseFilePipe({
        validators: [new FileTypeValidator({ fileType: '.(png|jpeg|jpg)' })],
      }),
    )
    image?: Express.Multer.File,
  ): Promise<IngredientModel> {
    return this.ingredientService.create(dto, image);
  }

以及从服务调用的创建方法:

async create(
    dto: CreateIngredientDto,
    image?: Express.Multer.File,
  ): Promise<IngredientModel> {
    try {
      return await ImageModel.transaction(async () => {
        if (image) {
          const imagePath = await ImageModel.query().insert({
            location: image.path,
          });
          return this.modelClass
            .query()
            .insert({ ...dto, imageId: imagePath.id });
        }
        return this.modelClass.query().insert({ ...dto });
      });
    } catch (err) {
      this.logger.error('An error occurred while creating the ingredient');
      return null;
    }
  }

【问题讨论】:

    标签: typescript file-upload nestjs multer


    【解决方案1】:

    您可以将 fileIsRequired 作为 false 传递给 ParseFilePipe 类。

    @UploadedFile(
      new ParseFilePipe({
        validators: [new FileTypeValidator({ fileType: '.(png|jpeg|jpg)' })],
        fileIsRequired: false,
      }),
    )
    
    

    【讨论】:

      猜你喜欢
      • 2022-01-07
      • 2020-01-06
      • 1970-01-01
      • 1970-01-01
      • 2020-03-04
      • 2014-11-03
      • 2020-04-09
      • 2022-08-15
      • 1970-01-01
      相关资源
      最近更新 更多