my problem is i cant compress the image before upload in the server cuz on sevrall reason
when of them is the file uploaded dosent includes buffer properity
the objective is to upload the image if and only if the resource created succufuly
ps: image is required when creating the resource
and before upload the image i wanna first compress it
handle compress file before upload it to the server logical problme
1- file upload service
here i handle the name of file
import { Injectable } from '@nestjs/common';
import { diskStorage } from 'multer';
import * as fs from 'fs';
import { editFileName } from 'libs/util/src/file-upload.utils';
export enum FileType {
IMAGE = 'image',
PDF = 'pdf',
}
@Injectable()
export class FilesUploaderService {
static getStorage(fileType: FileType) {
const isImage = fileType === FileType.IMAGE;
const destination = isImage ? 'images' : 'pdfs';
// Ensure the destination directory exists
const uploadDir = `./uploads/${destination}`;
const pathExists = fs.existsSync(uploadDir);
if (!pathExists) {
fs.mkdirSync(uploadDir, { recursive: true });
}
//handle compressionsss
return diskStorage({
destination: uploadDir,
filename: (req, file, cb) => {
if (!pathExists) return;
// copress the file
const newFile = isImage
? this.compressImage(file)
: this.compressPdf(file);
if (pathExists) {
console.log('File is about to be saved as:', newFile); // Log right before saving
editFileName(req, newFile, cb);
}
},
});
}
static compressImage(file: Express.Multer.File): Express.Multer.File {
console.log('compressing image', file);
return file;
}
static compressPdf(file: Express.Multer.File): Express.Multer.File {
return file;
}
}
2- file upload utils
import { extname } from 'path';
import * as fs from 'fs';
export const fsDelete = (path: string) => {
const fileExist = fs.existsSync(path);
if (fileExist) fs.unlinkSync(path);
};
export const imageFileFilter = (req, file, callback) => {
console.log('file:', file);
if (!file.originalname.match(/.(jpg|jpeg|png)$/)) {
console.log('file in imagefilter', file);
return callback(new Error('Only image files are allowed!'), false);
}
callback(null, true);
};
export const FileFilter = (req, file, callback) => {
if (!file.originalname.match(/.(pdf)$/)) {
return callback(new Error('Only pdf files are allowed!'), false);
}
callback(null, true);
};
export const editFileName = (req, file, callback) => {
const name = file.originalname.split('.')[0].replace(/s/g, '_'); // Replace spaces with underscores
const fileExtName = extname(file.originalname);
const randomName = Array(4)
.fill(null)
.map(() => Math.round(Math.random() * 16).toString(16))
.join('');
callback(null, `${name}-${randomName}${fileExtName}`);
};
3- controller for create a resource
@Post()
@ApiOperation({ summary: 'Create a new sector of activity' })
@ApiBody({ type: CreateSectorOfActivityDto })
@ApiConsumes('multipart/form-data')
@UseInterceptors(
FileInterceptor('image', {
storage: FilesUploaderService.getStorage(FileType.IMAGE),
fileFilter: imageFileFilter,
}),
)
async create(
@UploadedFile() file: Express.Multer.File,
@Body() createSectorOfActivityDto: CreateSectorOfActivityDto,
) {
createSectorOfActivityDto.image = file.path;
console.log('image controller', file);
return this.sectorOfActivityService.create(createSectorOfActivityDto);
}
4- service for create the resource
async handleFile(file: Express.Multer.File) {
if (!file) {
throw new NotFoundException(`File upload failed.`);
}
return file.path;
}
create(createSectorOfActivityDto: CreateSectorOfActivityDto) {
try {
this.sectorOfActivitiesRepository.createAndFlush(
createSectorOfActivityDto,
);
return Created();
} catch (error) {
throw new NotFoundException(`not created`);
}
}
this is some of my output
file: {
fieldname: 'image',
originalname: 'tree-736885_640.jpg',
encoding: '7bit',
mimetype: 'image/jpeg'
}
compressing image {
fieldname: 'image',
originalname: 'tree-736885_640.jpg',
encoding: '7bit',
mimetype: 'image/jpeg'
}
File is about to be saved as: {
fieldname: 'image',
originalname: 'tree-736885_640.jpg',
encoding: '7bit',
mimetype: 'image/jpeg'
}
image controller {
fieldname: 'image',
originalname: 'tree-736885_640.jpg',
encoding: '7bit',
mimetype: 'image/jpeg',
destination: './uploads/images',
filename: 'tree-736885_640-59a2.jpg',
path: 'uploads/images/tree-736885_640-59a2.jpg',
size: 58788
}