nestjs+swagger文件加载与附加的dto问题



我以前发过,但我的问题还没有解决,所以我编辑了这篇文章并重新发布。

@ApiOperation({ summary: 'upload' })
@ApiConsumes('multipart/form-data')
@ApiBody({ type: AddTestDto })
@Post('test')
@UseInterceptors(
FileFieldsInterceptor(
[
{ name: 'test1', maxCount: 5 },
{ name: 'test2', maxCount: 5 },
],
{
storage: multerS3({
s3: s3,
bucket: process.env.AWS_S3_BUCKET_NAME,
acl: 'public-read',
key: function (request, file, cb) {
cb(
null,
`test/${file.fieldname}/${uuid()}_${
file.originalname
}`,
);
},
}),
fileFilter: extensionHelper,
},
),
)
async uploadTest(
@Body() body: AddTestDto,
@UploadedFiles() file?: Express.MulterS3.File[],
) {
console.log(file);
console.log(body.additionalDto);
console.log(body.additionalDto[0]);
}
export class AddTestDto {
@ApiProperty({
type: 'file',
name: 'test1',
properties: {
file: {
type: 'string',
format: 'binary',
},
},
isArray: true,
})
@IsOptional()
test1: any[];
@ApiProperty({
name: 'test2',
type: 'file',
properties: {
file: {
type: 'string',
format: 'binary',
},
},
isArray: true,
})
@IsOptional()
test2: any[];
@ApiProperty({
type: AddDto,
isArray: true,
})
@Type(() => AddDto)
@IsOptional()
additionalDto: AddDto[];
}

代码如上所述,additionalto包括字符串和数字。下面是招摇画面

大摇大摆的形象

然后,我像上面那样发送数据并检查控制器中的console.log,文件看起来很好。

在第二个console.log中,数据显示为数组。

但是,最后一个console.log是typeof string,并且只显示一个'['字符。

我想通过apibody同时接收文件数组和dto数组。我该怎么办?

这似乎是Swagger的问题。在Content type:multipart/form-data,它将发送像

这样的对象数组
{
key1 : "value1",
key2 : "value2"
},
{
key1 : "value1-1",
key2 : "value2-1"
},
在字符串的开始和结束处缺少方括号

的。Nest会自动将对象字符串转换为json,但它不能理解上面的字符串,因为它不是json类型的验证。因此,我们需要手动变换它,使用一些自定义:

@ApiProperty({
type: AddDto,
isArray: true,
})
@Transform(({ value }) => {
const parsedObj = JSON.parse(`[${value}]`);
return parsedObj;
})
@Type(() => AddDto)
@IsOptional()
additionalDto: AddDto[];

最新更新