Изображения сохраняются в dist/uploads/image
main.ts
import { AppModule } from './modules/app.module';
import { NestFactory } from '@nestjs/core';
import { ValidateInputPipe } from './validators/validate.pipe';
async function startServer() {
const PORT = process.env.PORT || 5000
const app = await NestFactory.create(AppModule);
app.setGlobalPrefix("/api")
app.useGlobalPipes(new ValidateInputPipe())
app.enableCors()
await app.listen(PORT);
}
startServer();
file.service.ts
import { HttpException, HttpStatus, Injectable } from "@nestjs/common";
import * as path from "path"
import * as fs from "fs"
import * as uuid from "uuid"
export enum FileType {
IMAGE = "image",
VIDEO = "video",
AUDIO = "audio",
PDF = "pdf"
}
@Injectable()
export class FileService {
constructor() {}
createFile(type: FileType, file): string {
try {
const fileExtension = file.originalname.split(".").pop()
const fileName = uuid.v4() + "." + fileExtension
const filePath = path.resolve(__dirname, "..", "uploads", type)
if (!fs.existsSync(filePath)) fs.mkdirSync(filePath, {recursive: true})
fs.writeFileSync(path.resolve(filePath, fileName), file.buffer)
return type + "/" + fileName
} catch (error) {
throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR)
}
}
removeFile(filename: string) {}
}
file.module.ts
import { FileService } from './../services/file.service';
import { Module } from "@nestjs/common";
@Module({
providers: [FileService]
})
export class FileModule {}
courses.controller.ts
import { CoursesService } from './../services/courses.service';
import { Body, Controller, Delete, Get, Post, UploadedFile, UseInterceptors } from "@nestjs/common";
import { FileInterceptor } from '@nestjs/platform-express';
@Controller("/courses")
export class CoursesController {
constructor(private coursesService: CoursesService) {}
@Post("/create")
@UseInterceptors(FileInterceptor("logo"))
createCourse(@Body() dataCourse: any, @UploadedFile() logo: any) {
return this.coursesService.create(dataCourse, logo)
}
}