ticket-booking-be/src/common/files.service.ts
2025-04-06 17:55:09 +05:30

64 lines
2.1 KiB
TypeScript

import { Injectable } from '@nestjs/common';
import { diskStorage } from 'multer';
import { extname, join } from 'path';
import * as fs from 'fs';
@Injectable()
export class FilesService {
// Method to configure Multer's storage
getMulterStorage() {
return diskStorage({
destination: (req, file, cb) => {
// Define the upload path
const uploadPath = './uploads';
// Create the upload directory if it doesn't exist
if (!fs.existsSync(uploadPath)) {
fs.mkdirSync(uploadPath, { recursive: true });
}
// Set the destination directory for file storage
cb(null, uploadPath);
},
filename: (req, file, cb) => {
// Generate a unique file name based on the current timestamp
const fileName = Date.now() + extname(file.originalname);
cb(null, fileName);
},
});
}
// Method to filter file types based on MIME type and extension
fileFilter(req, file, cb) {
const allowedImageTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/jpg'];
const allowedVideoTypes = ['video/mp4', 'video/avi', 'video/mov'];
// Check if the file is an image or a video
if (allowedImageTypes.includes(file.mimetype) || allowedVideoTypes.includes(file.mimetype)) {
return cb(null, true); // Allow the file
} else {
return cb(new Error('Only images (jpg, png, gif) and videos (mp4, avi, mov) are allowed!'), false); // Reject the file
}
}
// Helper method to categorize the uploaded files into images and videos
categorizeFiles(files: Express.Multer.File[]): { image: string[]; video: string[] } {
const categorizedFiles = {
image: [],
video: [],
};
// Categorize files based on their extensions
files.forEach(file => {
const ext = extname(file.originalname).toLowerCase();
if (['.jpg', '.jpeg', '.png', '.gif'].includes(ext)) {
categorizedFiles.image.push(file.path); // Categorize as image
} else if (['.mp4', '.avi', '.mov'].includes(ext)) {
categorizedFiles.video.push(file.path); // Categorize as video
}
});
return categorizedFiles;
}
}