multer @nestjs/platform-express nestJs自带了
multer @types/multer 这两个需要安装
在upload Module 使用MulterModule register注册存放图片的目录
需要用到 multer 的 diskStorage 设置存放目录 extname 用来读取文件后缀 filename给文件重新命名
- import { Module } from '@nestjs/common';
- import { UploadService } from './upload.service';
- import { UploadController } from './upload.controller';
- import { MulterModule } from '@nestjs/platform-express'
- import {diskStorage} from 'multer'
- import { extname,join } from 'path';
- @Module({
- imports: [MulterModule.register({
- storage:diskStorage({
- destination:join(__dirname,"../images"),
- filename:(_,file,callback) => {
- const fileName = `${new Date().getTime() + extname(file.originalname)}`
- return callback(null,fileName)
- }
- })
- })],
- controllers: [UploadController],
- providers: [UploadService]
- })
- export class UploadModule { }
使用 UseInterceptors 装饰器 FileInterceptor是单个 读取字段名称 FilesInterceptor是多个
参数 使用 UploadedFile 装饰器接受file 文件
- import { Controller, Get, Post, Body, Patch, Param, Delete,UseInterceptors,UploadedFile } from '@nestjs/common';
- import { UploadService } from './upload.service';
- import {FileInterceptor} from '@nestjs/platform-express'
- @Controller('upload')
- export class UploadController {
- constructor(private readonly uploadService: UploadService) {}
- @Post('album')
- @UseInterceptors(FileInterceptor('file'))
- upload (@UploadedFile() file) {
- console.log(file)
- return true
- }
- }
useStaticAssets prefix 是虚拟前缀
- import { NestFactory } from '@nestjs/core';
- import { AppModule } from './app.module';
- import {NestExpressApplication} from '@nestjs/platform-express'
- import { join } from 'path'
- async function bootstrap() {
- const app = await NestFactory.create<NestExpressApplication>(AppModule);
- app.useStaticAssets(join(__dirname,'images'),{
- prefix:"/xiaoman"
- })
- await app.listen(3000);
- }
- bootstrap();