ExpressJs

⌘K
  1. Home
  2. Docs
  3. ExpressJs
  4. multer অ্যাডভান্স middlew...
  5. স্টোরেজ (helper) মেথড তৈরি করি

স্টোরেজ (helper) মেথড তৈরি করি

const multer = require('multer');
const path = require('path');
const fs = require('fs');

// 1. Helper method: Destination directory
const getDestination = () => {
  const uploadPath = path.join(__dirname, '../uploads');
  if (!fs.existsSync(uploadPath)) {
    fs.mkdirSync(uploadPath, { recursive: true });
  }
  return uploadPath;
};

// 2. Helper method: Generate a unique file name
const generateFileName = (file) => {
  const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
  const ext = path.extname(file.originalname);
  return file.fieldname + '-' + uniqueSuffix + ext;
};

// Multer স্টোরেজ কনফিগারেশন
const storage = multer.diskStorage({
  // Destination ফাংশন গন্তব্য ডিরেক্টরি নির্ধারণ করে
  destination: (req, file, cb) => {
    cb(null, getDestination());
  },
  // Filename ফাংশন ফাইলের নাম নির্ধারণ করে
  filename: (req, file, cb) => {
    cb(null, generateFileName(file));
  }
});

module.exports = storage;

How can we help?