Nestjs文件上传

Nestjs内置了文件上传的方法,Nestjs中通过file-upload可以实现单文件上传,多文件上传

Nestjs file-upload官方文档,https://docs.nestjs.com/techniques/file-upload

1、Nestjs单文件上传

前端html代码

上传图片的时候From表单中需要配置enctype="multipart/form-data"
	

		<form action="user/add" method="post" enctype="multipart/form-data">    
			<input type="text" name="title1" id="" placeholder="新闻标题"/>    
	
			<input type="text" name="keywords" id="" placeholder="关键词"/>       
	
			<input type="text" name="author" id="" placeholder="作者" />
		   
			<input type="file" name="pic" id="" />
		   
			<input type="text" name="status" id="" placeholder="状态" />       
	
			<input type="submit" value="提交">        
		</form>

		
	

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 '上传成功';
}