handle compress file before upload it to the server logical problme

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
}

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật