安装依赖包:
pnpm add multer
pnpm add -D @types/multer
src下新建upload文件夹,文夹中新建upload.module.ts和upload.controller.ts文件
upload.module.ts文件代码:
import { Module } from "@nestjs/common";
import { MulterModule } from "@nestjs/platform-express";
import { UploadController } from "./upload.controller";
import { diskStorage } from 'multer'
import {extname} from 'path'
@Module({
imports: [MulterModule.register({
storage: diskStorage({
//文件储存位置
destination: 'uploads/' + new Date().getFullYear()+'/' + Number(new Date().getMonth()+1),
//文件名定制
filename: (req, file, callback) => {
const path = Date.now() + '-' + Math.round(Math.random() * 1e10) + extname(file.originalname)
callback(null, path)
},})
})],
controllers: [UploadController]
})
export class UploadModule {}
upload.controller.ts文件代码:
import { Controller,Post, UseInterceptors, UploadedFile } from '@nestjs/common';
import {FileInterceptor} from '@nestjs/platform-express'
@Controller('upload')
export class UploadController {
@Post('file')
@UseInterceptors(FileInterceptor('file'))
uploadFile(@UploadedFile() file) {
return file.destination + file.filename
}
}