File Upload not showing in swagger (Nest JS)

huangapple go评论69阅读模式
英文:

File Upload not showing in swagger (Nest JS)

问题

我已经实现了一个文件上传功能,以及其他数据,想尝试在Swagger中使用API,但它没有显示文件上传的模态框。

我的控制器文件如下:

@UseInterceptors(FileInterceptor('file'))
@Put()
@ApiOperation({
  summary: '用于更新检查模板中的数值的端点',
})
@HttpCode(HttpStatus.OK)
async updateChecklistTemplate(
  @Body() setFieldValueDto: UpdateChecklistValueDto,
  @UploadedFile() file: Express.Multer.File,
  @Request() req,
) {
  return await this.checklistTemplatesService.setFieldValue(
    setFieldValueDto,
    req.user.id,
    file,
  );
}

我的DTO文件:

import {
  IsArray,
  IsBoolean,
  IsMongoId,
  IsNotEmpty,
  IsOptional,
  IsString,
} from 'class-validator';
import { ApiProperty } from '@nestjs/swagger';

export class UpdateChecklistValueDto {
  @ApiProperty()
  @IsString()
  @IsNotEmpty()
  @IsMongoId()
  readonly id: string;

  @ApiProperty()
  @IsBoolean()
  @IsNotEmpty()
  readonly isImage: boolean;

  @ApiProperty()
  @IsString()
  @IsNotEmpty()
  readonly entity: string;

  @ApiProperty()
  @IsString()
  @IsNotEmpty()
  readonly value: string;

  @ApiProperty({ type: 'string', format: 'binary', required: true })
  file: Express.Multer.File;
}

我对此还不太熟悉,如果您能指出任何遗漏的部分,我将不胜感激。非常感谢您的帮助 File Upload not showing in swagger (Nest JS)

英文:

I have implemented a file upload function along other data , wanted to try out the api in swagger but it does not show the file upload modal.
My controller file is as follows :

@UseInterceptors(FileInterceptor('file'))
  @Put()
  @ApiOperation({
    summary: 'Endpoint used to update values in the checklist Template',
  })
  @HttpCode(HttpStatus.OK)
  async updateChecklistTemplate(
    @Body() setFieldValueDto: UpdateChecklistValueDto,
    @UploadedFile() file: Express.Multer.File,
    @Request() req,
    
  ) {
    return await this.checklistTemplatesService.setFieldValue(
      setFieldValueDto,
      req.user.id,
      file,
    );
  }
 

My DTO file :

import {
  IsArray,
  IsBoolean,
  IsMongoId,
  IsNotEmpty,
  IsOptional,
  IsString,
} from 'class-validator';
import { ApiProperty } from '@nestjs/swagger';
export class UpdateChecklistValueDto {
  @ApiProperty()
  @IsString()
  @IsNotEmpty()
  @IsMongoId()
  readonly id: string;

  @ApiProperty()
  @IsBoolean()
  @IsNotEmpty()
  readonly isImage: boolean;

  @ApiProperty()
  @IsString()
  @IsNotEmpty()
  readonly entity: string;

  @ApiProperty()
  @IsString()
  @IsNotEmpty()
  readonly value: string;

  @ApiProperty({ type: 'string', format: 'binary', required: true })
  file: Express.Multer.File;
}

I am kind of new to this, appreciate it if you could point out anything missing here.
Thank you so much in advance File Upload not showing in swagger (Nest JS)

答案1

得分: 1

你需要使用@ApiConsumes@ApiBody装饰器。请查看NestJS文档中的“文件上传”部分。你的情况可能如下所示,但也请根据你的特定需求查看Swagger文档进行自定义。

import { ApiBody, ApiConsumes } from '@nestjs/swagger';
// ...
@UseInterceptors(FileInterceptor('file'))
@Put()
@ApiOperation({
  summary: '用于更新清单模板中的值的端点',
})
@ApiConsumes('multipart/form-data')
@ApiBody({
  schema: {
    type: 'object',
    properties: {
      file: {     // 与FileInterceptor('file')中的字符串匹配
        type: 'string',
        format: 'binary',
      },
    },
  },
})
@HttpCode(HttpStatus.OK)
async updateChecklistTemplate(

NestJS文档建议使用如下方式:

@ApiBody({
  description: '猫的列表',
  type: FileUploadDto,
})

// 其中FileUploadDto的定义如下:

class FileUploadDto {
  @ApiProperty({ type: 'string', format: 'binary', required: true })
  file: any;
}

// 你的情况
export class UpdateChecklistValueDto extends FileUploadDto {
  // ...
}

对于一个路由有这么多装饰器,你可以创建一个自定义装饰器来处理文件上传,如下所示:

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

export function SingleFile(fileName?: string) {
  return applyDecorators(
    ApiConsumes('multipart/form-data'),
    ApiFile(fileName),
    UseInterceptors(FileInterceptor('file')),
  );
}

// 你的控制器路由
@SingleFile()
@Put()
@ApiOperation({
  summary: '用于更新清单模板中的值的端点',
})
@HttpCode(HttpStatus.OK)
async updateChecklistTemplate(
英文:

You need to use @ApiConsumes and @ApiBody decorators. See the NestJS documentation for File uploads. Your case might look something like this but please also check the swagger docs to customise based on your specific requirements

import { ApiBody, ApiConsumes } from '@nestjs/swagger';
...
@UseInterceptors(FileInterceptor('file'))
@Put()
@ApiOperation({
  summary: 'Endpoint used to update values in the checklist Template',
})
@ApiConsumes('multipart/form-data')
@ApiBody({
  schema: {
    type: 'object',
    properties: {
      file: {      <----- matches the string in FileInterceptor('file')
        type: 'string',
        format: 'binary',
      },
    },
  },
})
@HttpCode(HttpStatus.OK)
async updateChecklistTemplate(

The nestjs docs suggest usage like this:

@ApiBody({
  description: 'List of cats',
  type: FileUploadDto,
})

// Where FileUploadDto is defined as follows:

class FileUploadDto {
  @ApiProperty({ type: 'string', format: 'binary', required: true })
  file: any;
}

// Your case
export class UpdateChecklistValueDto extends FileUploadDto {
...
}

With this many decorators for one route, you could create a custom decorator to handle the file upload like so:

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

export function SingleFile(fileName?: string) {
  return applyDecorators(
    ApiConsumes('multipart/form-data'),
    ApiFile(fileName),
    UseInterceptors(FileInterceptor('file')),
  );
}

// Your controller route
@SingleFile()
@Put()
@ApiOperation({
  summary: 'Endpoint used to update values in the checklist Template',
})
@HttpCode(HttpStatus.OK)
async updateChecklistTemplate(

huangapple
  • 本文由 发表于 2023年3月1日 15:14:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/75600551.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定