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
相关产品推荐
相关产品推荐

