我想用swagger创建上传,使用DTO并将二进制文件保存在我的MongoDB 中
我的DTO是:
import { ApiProperty } from '@nestjs/swagger';
import { Expose } from 'class-transformer';
import { IsNotEmpty, IsOptional } from 'class-validator';
export class GatewayDto {
@ApiProperty({ default: 'foo' })
@IsNotEmpty()
@Expose()
name: string;
@ApiProperty({default: 'XXXX:YYYY'})
@IsNotEmpty()
@Expose()
token: string;
@ApiProperty({default: '123'})
@IsNotEmpty()
@Expose()
channelId: string;
@ApiProperty({ default: true })
@IsNotEmpty()
@Expose()
public: string;
@Expose()
@IsNotEmpty()
logo: any;
}
我的控制器是:
@Post('/')
@ApiConsumes('multipart/form-data')
@ApiBody({
schema: {
type: 'object',
properties: {
name: {
type: 'string',
default: 'foo'
},
token: {
type: 'string',
default: '11:22'
},
channelId: {
type: 'string',
default: '1234'
},
public: {
type: 'string',
default: 'true'
},
logo: {
type: 'string',
format: 'binary',
},
},
},
})
@UseInterceptors(FileInterceptor('logo'))
@HttpCode(HttpStatus.CREATED)
@ApiCreatedResponse(GatewayConfigSwagger.API_CREATE_GATEWAY)
//@Serialize(GatewayDto)
public async create(
@UploadedFile('file') file,
@Body() data: GatewayDto,
@Request() request
) {
console.log(data);
if (file) {
data['logo'] = file.buffer;
}
//return this.gatewayService.create(request.user.userId._id, data);
}
当我创建请求时,我会收到以下错误:
"logo should not be empty"
我的卷发是:
curl -X 'POST'
'http://localhost:3001/api/v1/gateways'
-H 'accept: application/json'
-H 'Authorization: Bearer xxx
-H 'Content-Type: multipart/form-data'
-F 'name=foo'
-F 'token=11:22'
-F 'channelId=1234'
-F 'public=true'
-F 'logo=@image.png;type=image/png'
如果我从DTO中删除徽标字段,我就可以存储我的图像。
我试图根据这个答案创建一个拦截器。文件与Swagger NestJs 中的其他数据一起上传
import { BadGatewayException, CallHandler, ExecutionContext, Injectable, NestInterceptor, UnauthorizedException } from "@nestjs/common";
import { catchError, map, Observable, throwError } from "rxjs";
export interface Response<T> {
statusCode: number;
data: T;
}
@Injectable()
export class FileExtender implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
const req = context.switchToHttp().getRequest();
console.log(req.body)
return next.handle();
}
}
我的req.body没有标志字段
更新
我用更新了我的拦截器
import { BadGatewayException, CallHandler, ExecutionContext, Injectable, NestInterceptor, UnauthorizedException } from "@nestjs/common";
import { catchError, map, Observable, throwError } from "rxjs";
export interface Response<T> {
statusCode: number;
data: T;
}
@Injectable()
export class FileExtender implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
const req = context.switchToHttp().getRequest();
req.body['logo'] = req.file.buffer;
console.log(req.body)
return next.handle();
}
}
现在它起作用了,但这是最好的做法吗?
尝试对DTO文件中的logo
属性使用@IsOptional
验证器。它用于标记可为null的字段。如果是null
或undefined
,则验证将通过,否则将按照其他验证器执行。应用程序逻辑必须相应地处理此问题。
您可以在这里查看所有可用的验证器。您可以在任何DTO类属性上组合任意数量的它们。