npm install multer
npm install @types/multer --save-dev
nest g res upload
upload.module.ts
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 { join, extname } 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 { }
upload.controller.ts
import { Controller, Get, Post, Body, Patch, Param, Delete, UseInterceptors, UploadedFile } from '@nestjs/common';
import { UploadService } from './upload.service';
import { CreateUploadDto } from './dto/create-upload.dto';
import { UpdateUploadDto } from './dto/update-upload.dto';
import { FileInterceptor } from '@nestjs/platform-express';
@Controller('upload')
export class UploadController {
constructor(private readonly uploadService: UploadService) { }
@Post()
@UseInterceptors(FileInterceptor('file')) // 'file'为前端表单字段名称
async uploadFile(@UploadedFile() file) {
console.log('file', file);
console.log(`${file.originalname} uploaded successfully.`);
return `Successfully uploaded ${file.originalname}`;
}
}
main.ts
import { VersioningType } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import * as session from 'express-session';
import { NestExpressApplication } from '@nestjs/platform-express/interfaces';
import { join } from 'path';
async function bootstrap() {
const app = await NestFactory.create<NestExpressApplication>(AppModule);
app.useStaticAssets(join(__dirname, 'images'),{
prefix: "/img"
});
await app.listen(3000);
}
bootstrap();