diff --git a/BE/src/file/file.module.ts b/BE/src/file/file.module.ts new file mode 100644 index 0000000..496fb49 --- /dev/null +++ b/BE/src/file/file.module.ts @@ -0,0 +1,8 @@ +import { FileService } from './file.service'; +import { Module } from '@nestjs/common'; + +@Module({ + providers: [FileService], + exports: [FileService], +}) +export class FileModule {} diff --git a/BE/src/file/file.service.ts b/BE/src/file/file.service.ts new file mode 100644 index 0000000..bd83125 --- /dev/null +++ b/BE/src/file/file.service.ts @@ -0,0 +1,35 @@ +import { BadRequestException, Injectable } from '@nestjs/common'; +import { unlink, writeFile } from 'fs/promises'; +import { v4 as uuidv4 } from 'uuid'; + +@Injectable() +export class FileService { + private readonly basePath = 'static/'; + + constructor() {} + + private generateFilename(originalname: string) { + const extension = originalname.split('.').pop(); + const uniqueId = uuidv4(); + return `${uniqueId}.${extension}`; + } + + async upload(path: string, file: Express.Multer.File) { + const filePath = + this.basePath + path + this.generateFilename(file.originalname); + await writeFile(filePath, file.buffer); + + return { + imageUrl: filePath, + path: filePath, + }; + } + + async getImageUrl(key: string): Promise { + return this.basePath + key; + } + + async delete(path: string) { + await unlink(this.basePath + path); + } +}