0%

NestJS 上传文件

问题

NestJS 接收单个文件的上传和批量多个文件上传,及上传文件添加额外参数

解决

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import {
Controller,
Post,
Body,
UseInterceptors,
UploadedFile,
UploadedFiles,
Request,
UseGuards,
StreamableFile,
Get,
Response,
Param,
} from '@nestjs/common';
import { FileInterceptor, FilesInterceptor } from '@nestjs/platform-express';

// 单文件 + 其他字段
@Post('uploadPdf')
@UseInterceptors(FileInterceptor('pdf', { dest: './uploads' }))
async uploadPdf(@UploadedFile() file, @Body() body) {
console.log(file, body);
}

// 多文件 + 其他字段
@Post('upload')
@UseInterceptors(FileFieldsInterceptor([
{ name: 'avatar', maxCount: 1 },
{ name: 'background', maxCount: 1 },
]))
uploadFile(@UploadedFiles() files: { avatar?: Express.Multer.File[], background?: Express.Multer.File[] }) {
console.log(files);
}

参考文章