You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NestJS如何实现REST API接口的可选文件上传?

NestJS实现可选文件上传(同时保留必填请求体)

要让文件上传变为可选,只需在ParseFilePipeBuilder的配置中添加optional: true参数即可,修改后的代码如下:

@UseGuards(JwtAuthGuard)
@Post('create')
@UseInterceptors(FileInterceptor('file', { }))
async createPost(
  @Req() req: any, 
  @Body() createPostDto: CreatePostDto, 
  @UploadedFile(
    new ParseFilePipeBuilder()
      .addMaxSizeValidator({ maxSize: 2048 })
      .build({ 
        errorHttpStatusCode: HttpStatus.UNPROCESSABLE_ENTITY,
        optional: true // 关键配置:将文件设为可选
      })
  ) file?: Express.Multer.File // 可选:给参数添加TypeScript可选标记
) {
  return await this.postsService.createPost(req.user, createPostDto, file);
}

核心说明

  • 默认状态下,ParseFilePipe会强制校验文件是否存在,添加optional: true后,NestJS会允许请求中不携带file字段
  • 已配置的文件验证规则(比如这里的大小限制)依然有效:如果上传了文件,会触发校验;未上传则跳过
  • 给file参数加上?可选标记,能让TypeScript语法更严谨

内容的提问来源于stack exchange,提问作者jacobbrds

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 01:37:35