Nestjs上传文件图片

发布于 1周前 作者 phonegap100 来自 分享

Nestjs文件上传、单个文件上传 多个文件上传

一、Nestjs file-upload官方文档

https://docs.nestjs.com/techniques/file-upload

二、单个文件上传

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

三、多文件上传

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

四、注意事项

上传图片的时候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>
回到顶部