Nestjs内置了文件上传的方法,Nestjs中通过file-upload可以实现单文件上传,多文件上传
Nestjs file-upload官方文档,https://docs.nestjs.com/techniques/file-upload
前端html代码
上传图片的时候From表单中需要配置enctype="multipart/form-data"2、nestjs文件上传后端代码
import { Controller, Get, Render, Post,UseInterceptors,UploadedFile} from '@nestjs/common'; import { FileInterceptor,FilesInterceptor } from '@nestjs/platform-express'; @Post('doAdd') @UseInterceptors(FileInterceptor('pic')) addUser(@UploadedFile() file,@Body() body){ console.log(body); console.log(file); const writeImage = createWriteStream(join(__dirname, '..','../public/upload', `${file.originalname}`)) writeImage.write(file.buffer) return '上传成功'; }
3、nestjs多文件上传
import { Controller, Get, Render, Post,UseInterceptors,UploadedFiles} from '@nestjs/common'; import { FileInterceptor,FilesInterceptor } from '@nestjs/platform-express'; @Post('doAddAll') @UseInterceptors(FilesInterceptor('pic')) addAllUser(@UploadedFiles() files,@Body() body){ for (const file of files) { const writeImage = createWriteStream(join(__dirname, '../../', 'public/upload', `${body.name}-${Date.now()}-${file.originalname}`)); writeImage.write(file.buffer); } return '上传成功'; }