7.nestjs文件上传

nestjs文件上传

文件上传

单个文件上传

// 1.依赖引入 UseInterceptors, UploadedFile, FileInterceptor
import { Controller, Get, Post, Render, Body, UseInterceptors, UploadedFile } from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
// 3.将上传的图片放到某个文件夹
import { createWriteStream } from 'fs';
import { join } from 'path';

@Controller('upload')
export class UploadController {
    @Get() 
    @Render('default/upload')
    index(){}

    @Post('doAdd')
    // 2.使用
    // 注意:必须在form的属性中配置enctype="multipart/form-data"
    @UseInterceptors(FileInterceptor('pic')) // 配置上传图片的名称
    doAdd(@Body() body, @UploadedFile() file){
        console.log('文件: ', file);
        console.log('body: ', body);
        console.log('__dirname: ', __dirname);
        // 4.将上传的图片放到某个文件夹
        var writeStream = createWriteStream(join(__dirname, '../../public/upload', `${Date.now()}-${file.originalname}`))
        writeStream.write(file.buffer);
        return '上传图片成功';
    }
}

多文件上传

// 1.依赖引入 UseInterceptors, UploadedFiles, FilesInterceptor
import { Controller, Get, Post, Render, Body, UseInterceptors, UploadedFiles } from '@nestjs/common';
import { FilesInterceptor } from '@nestjs/platform-express';
// 3.将上传的图片放到某个文件夹
import { createWriteStream } from 'fs';
import { join } from 'path';

@Controller('uploadmany')
export class UploadmanyController {
    @Get() 
    @Render('default/uploadmany')
    index(){}

    @Post('doAdd')
    // 2.使用
    // 注意:必须在form的属性中配置enctype="multipart/form-data"
    @UseInterceptors(FilesInterceptor('pic'))
    doAdd(@Body() body, @UploadedFiles() files){
        console.log('body: ', body);
        console.log('files: ', files);
        // 4.循环放入图片
        for(const file of files) {
            const writeImage = createWriteStream(join(__dirname, '../../public/upload', `${Date.now()}-${file.originalname}`));
            writeImage.write(file.buffer);
        }
        return '上传图片成功';
    }
}
上一篇:NestJS企业微信消息推送


下一篇:[电子书] 《Android编程入门很简单》