13-上传图片-静态目录
大约 1 分钟
Nestjs 上传图片
1. 主要会用到两个包
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 { }
2.controller 使用
使用 UseInterceptors 装饰器 FileInterceptor 是单个 读取字段名称 FilesInterceptor 是多个
参数 使用 UploadedFile 装饰器接受 file 文件
import {
Controller,
Post,
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;
}
}
静态目录
3.生成静态目录访问上传之后的图片
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();