簡體   English   中英

如何將 POST api 中的文件和其他輸入正確添加到 swagger 中?

[英]How to add file and other inputs in a POST api into swagger properly?

我正在嘗試使用 NestJS 為文件上傳 API 創建 swagger 文檔。

這是我目前在 controller 中的內容:

@ApiTags('files')
@Controller('files')
export class FilesController {

    @ApiConsumes('multipart/form-data')
    @ApiCreatedResponse({description: "This api creates a file in the system"})
    @Post('upload')
    @UseInterceptors(FileInterceptor('file'))
    uploadFile(@UploadedFile() file, @Body() fileInfo: UploadFileDto) {
        console.log(file);
        console.log(fileInfo);  
    }
}

在我的 DTO 文件中:

import { IsString } from 'class-validator'
import { ApiProperty } from '@nestjs/swagger'

export class UploadFileDto {
    @IsString()
    communityName: string

    @IsString()
    type: string

    @ApiProperty({type:"file"})
    file: any;
}

這樣,它可以正確顯示 swagger 中的所有內容(並且可以正常工作)。 但是,如您所見,我的 DTO class 和 function 變量中有一個冗余的“文件”變量。 如果我從 DTO 中刪除“文件”屬性,則 swagger UI 不會將此參數識別為文件輸入。 如果我從 function 參數中刪除它,那么它會顯示在 swagger UI 中,但 controller 沒有收到上傳的文件。 有沒有辦法糾正這個問題?

謝謝。

我剛剛遇到了同樣的問題,多虧了你,我實際上解決了我的問題。

我的 controller 看起來如下

@Controller('files')
@ApiTags('files')
export class FilesController
{
    @Post('import')
    @ApiConsumes("multipart/form-data")
    @UseInterceptors(FileInterceptor('file',
        {
            storage: diskStorage({
                destination: './tmp', 
                filename: (req, file, cb) => {
                    const randomName = Array(32).fill(null).map(() => (Math.round(Math.random() * 16)).toString(16)).join('')
                    return cb(null, `${randomName}${extname(file.originalname)}`)
                }
            })
        }
    ))
    async upload(
        @Body() uploadDto: UploadDto,
        @UploadedFile() file: Express.Multer.File
    ): Promise<void>
    {
        console.log(importDto);
        console.log(file);
    }
}

還有我的 DTO

import { IsString } from 'class-validator';
import { ApiProperty } from '@nestjs/swagger';

export class ImportDto {

    @IsString()
    name: string;

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

請注意,唯一真正的變化是 DTO 中的@ApiProperty() 那成功了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM