Skip to content

NestJS 文件上传:单文件、多文件及额外参数

Published: at 10:57 AMSuggest Changes

问题

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);
}

参考文章


Previous Post
JS 反转义实现与研究
Next Post
JS 视频播放事件拦截