no image

nestjs swagger upload file

数字有颜色 | 
2022-10-21 14:16:42

找了半天方法下面这个可以

https://github.com/nestjs/swagger/issues/417#issuecomment-562869578

@Post('upload')
  @ApiConsumes('multipart/form-data')
  @ApiBody({
    schema: {
      type: 'object',
      properties: {
        file: {
          type: 'string',
          format: 'binary',
        },
      },
    },
  })
  @UseInterceptors(FileInterceptor('file'))
  uploadFile(@UploadedFile('file') file) {
    console.log(file);
  }

 

你也可以定义一个装饰器

 

import { ApiBody } from '@nestjs/swagger';

export const ApiFile = (fileName: string = 'file'): MethodDecorator => (
  target: any,
  propertyKey: string,
  descriptor: PropertyDescriptor,
) => {
  ApiBody({
    schema: {
      type: 'object',
      properties: {
        [fileName]: {
          type: 'string',
          format: 'binary',
        },
      },
    },
  })(target, propertyKey, descriptor);
};

 

@Post('upload')
  @ApiConsumes('multipart/form-data')
  @ApiFile()
  @UseInterceptors(FileInterceptor('file'))
  uploadFile(@UploadedFile('file') file) {
    console.log(file);
  }

 

也可以指定对应的参数名称

@Post('upload')
  @ApiConsumes('multipart/form-data')
  @ApiFile('avatar')
  @UseInterceptors(FileInterceptor('avatar'))
  uploadFile(@UploadedFile() file) {
    console.log(file);
  }

 

 

 

 

 

 

文章列表 sitemap