دوره‌ها / Node.js / اعتبارسنجی فایل (File Validation)

اعتبارسنجی فایل (File Validation)

15 دقیقه Article

اعتبارسنجی فایل: Validation فایل‌های آپلود شده ✅

اعتبارسنجی فایل برای اطمینان از نوع و اندازه فایل ضروریه!

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

// تنظیم file filter
const fileFilter = (req, file, cb) => {
    // فقط تصاویر
    const allowedTypes = /jpeg|jpg|png|gif/;
    const extname = allowedTypes.test(path.extname(file.originalname).toLowerCase());
    const mimetype = allowedTypes.test(file.mimetype);
    
    if (extname && mimetype) {
        return cb(null, true);
    } else {
        cb(new Error('Only image files are allowed!'));
    }
};

// تنظیم limits
const upload = multer({
    storage: storage,
    fileFilter: fileFilter,
    limits: {
        fileSize: 5 * 1024 * 1024 // 5MB
    }
});

// استفاده
app.post('/upload', upload.single('file'), (req, res) => {
    res.json({ message: 'File uploaded' });
});

Error Handling:

app.post('/upload', upload.single('file'), (req, res) => {
    // File validation
}, (err, req, res, next) => {
    if (err instanceof multer.MulterError) {
        if (err.code === 'LIMIT_FILE_SIZE') {
            return res.status(400).json({ error: 'File too large' });
        }
    }
    res.status(400).json({ error: err.message });
});
✅ یاد گرفتید: File validation برای امنیت ضروریه!

آماده رفتن به درس بعدی هستید؟

این درس را به پایان رساندید و می‌توانید به درس بعدی بروید.

برای ذخیره پیشرفت وارد شوید