|
| 1 | +import { Request, Response } from 'express' |
| 2 | + |
| 3 | +import crypto from 'crypto' |
| 4 | +import multer from 'multer' |
| 5 | +import path from 'path' |
| 6 | + |
| 7 | +const storageConfig = multer.diskStorage({ |
| 8 | + destination: (_, __, callBack) => { |
| 9 | + callBack(null, 'uploads/') |
| 10 | + }, |
| 11 | + filename: (_, file, callBack) => { |
| 12 | + const fileExt = path.extname(file.originalname) |
| 13 | + const fileName = `user-document-${crypto.randomUUID()}${fileExt}` |
| 14 | + callBack(null, fileName) |
| 15 | + }, |
| 16 | +}) |
| 17 | + |
| 18 | +const fileFilter = ( |
| 19 | + _: Request, |
| 20 | + file: Express.Multer.File, |
| 21 | + cb: multer.FileFilterCallback, |
| 22 | +) => { |
| 23 | + const allowedTypes = ['image/jpeg', 'image/png', 'application/pdf'] |
| 24 | + if (allowedTypes.includes(file.mimetype)) { |
| 25 | + cb(null, true) |
| 26 | + } else { |
| 27 | + cb(new Error('Invalid file type. Only JPEG, PNG, and PDF are allowed.')) |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +export const uploadSingle = multer({ |
| 32 | + storage: storageConfig, |
| 33 | + fileFilter, |
| 34 | + limits: { fileSize: 5 * 1024 * 1024 }, |
| 35 | +}).single('document') |
| 36 | + |
| 37 | +export const uploadMultipleDocs = multer({ |
| 38 | + storage: storageConfig, |
| 39 | + fileFilter, |
| 40 | + limits: { fileSize: 5 * 1024 * 1024 }, |
| 41 | +}).array('documents', 10) |
| 42 | + |
| 43 | +export function handleMulterErrorMessages(err: any, res: Response): Response { |
| 44 | + if (err instanceof multer.MulterError) { |
| 45 | + switch (err.code) { |
| 46 | + case 'LIMIT_FILE_SIZE': |
| 47 | + return res.status(400).json({ error: 'File size exceeds the limit!' }) |
| 48 | + case 'LIMIT_FILE_COUNT': |
| 49 | + return res.status(400).json({ error: 'Too many files uploaded!' }) |
| 50 | + case 'LIMIT_UNEXPECTED_FILE': |
| 51 | + return res.status(400).json({ error: 'Unexpected file uploaded!' }) |
| 52 | + default: |
| 53 | + return res |
| 54 | + .status(400) |
| 55 | + .json({ error: 'Unexpected error was occurred while uploading!' }) |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + return res.status(500).json({ error: 'An unknown error occurred!' }) |
| 60 | +} |
0 commit comments