问题
NestJS 接收单个文件的上传和批量多个文件上传,及上传文件添加额外参数
解决
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);
}
参考文章
- https://docs.nestjs.com/techniques/file-upload
- https://www.joshmorony.com/handling-multiple-file-uploads-with-nest-js/
- https://notiz.dev/blog/type-safe-file-uploads
- https://eliteionic.com/tutorials/uploading-files-to-a-nest-js-backend/
- https://gabrieltanner.org/blog/nestjs-file-uploading-using-multer