Im' 使用 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 向我的端点提交请求时
我从我的 NestJS 服务器收到这个 400 响应...
{
"message": "Unexpected field",
"error": "Bad Request",
"statusCode": 400
}
设置我的 NestJS 端点以接受这两个文件的正确方法是什么?
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[] },
) {
...
}