text-dataset-tiny-code-script-py-format
/
ysnrfd_messenger
/BACKUP4
/backend
/src
/middleware
/upload.js
| const multer = require('multer'); | |
| const path = require('path'); | |
| const { v4: uuidv4 } = require('uuid'); | |
| // Configure storage | |
| const storage = multer.diskStorage({ | |
| destination: (req, file, cb) => { | |
| cb(null, 'uploads/'); | |
| }, | |
| filename: (req, file, cb) => { | |
| const uniqueName = `${uuidv4()}${path.extname(file.originalname)}`; | |
| cb(null, uniqueName); | |
| } | |
| }); | |
| // File filter | |
| const fileFilter = (req, file, cb) => { | |
| const allowedTypes = { | |
| 'image/jpeg': true, | |
| 'image/jpg': true, | |
| 'image/png': true, | |
| 'image/gif': true, | |
| 'image/webp': true, | |
| 'audio/mpeg': true, | |
| 'audio/wav': true, | |
| 'audio/ogg': true, | |
| 'audio/mp4': true, | |
| 'application/pdf': true, | |
| 'text/plain': true, | |
| 'text/markdown': true | |
| }; | |
| if (allowedTypes[file.mimetype]) { | |
| cb(null, true); | |
| } else { | |
| cb(new Error(`File type ${file.mimetype} is not supported`), false); | |
| } | |
| }; | |
| const upload = multer({ | |
| storage, | |
| fileFilter, | |
| limits: { | |
| fileSize: 50 * 1024 * 1024 // 50MB max file size | |
| } | |
| }); | |
| // Error handling middleware for multer | |
| const handleUploadError = (error, req, res, next) => { | |
| if (error instanceof multer.MulterError) { | |
| if (error.code === 'LIMIT_FILE_SIZE') { | |
| return res.status(400).json({ error: 'File too large. Maximum size is 50MB.' }); | |
| } | |
| return res.status(400).json({ error: `Upload error: ${error.message}` }); | |
| } | |
| if (error) { | |
| return res.status(400).json({ error: error.message }); | |
| } | |
| next(); | |
| }; | |
| module.exports = { upload, handleUploadError }; |