Created
May 1, 2024 11:08
-
-
Save Davenchy/df8b10a0752dae68517ea4f54a0ce310 to your computer and use it in GitHub Desktop.
Multer Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require('express'); | |
const multer = require('multer'); | |
const { v4: uuidv4 } = require('uuid'); | |
const fs = require('fs'); | |
const path = require('path'); | |
const Resource = require('./models/Resource'); // Assuming you have a Resource model defined | |
const app = express(); | |
// Set up multer storage configuration | |
const storage = multer.diskStorage({ | |
destination: function (req, file, cb) { | |
cb(null, 'uploads/'); | |
}, | |
filename: function (req, file, cb) { | |
const filename = uuidv4() + path.extname(file.originalname); | |
cb(null, filename); | |
} | |
}); | |
const upload = multer({ | |
storage: storage, | |
limits: { fileSize: 5 * 1024 * 1024 } // 5MB file size limit | |
}).single('pdfFile'); | |
// Endpoint to handle file upload | |
app.post('/upload', (req, res) => { | |
upload(req, res, async function (err) { | |
if (err instanceof multer.MulterError) { | |
// A multer error occurred (e.g., file size exceeded limit) | |
return res.status(400).json({ error: 'File size exceeded limit' }); | |
} else if (err) { | |
// An unknown error occurred | |
return res.status(500).json({ error: 'Unknown error occurred' }); | |
} | |
// Check if file is not provided | |
if (!req.file) { | |
return res.status(400).json({ error: 'No file provided' }); | |
} | |
// Check if file is not a PDF | |
if (req.file.mimetype !== 'application/pdf') { | |
// Delete uploaded file | |
fs.unlinkSync(req.file.path); | |
return res.status(400).json({ error: 'File must be a PDF' }); | |
} | |
// Save file information to database | |
const resource = new Resource({ | |
originalName: req.file.originalname, | |
filename: req.file.filename, | |
size: req.file.size, | |
uploadedAt: new Date(), | |
creator: req.user // Assuming you have user authentication and req.user contains user info | |
}); | |
try { | |
await resource.save(); | |
res.status(200).json({ message: 'File uploaded successfully' }); | |
} catch (error) { | |
// If an error occurred while saving to the database | |
// Delete uploaded file | |
fs.unlinkSync(req.file.path); | |
res.status(500).json({ error: 'Failed to save file information to database' }); | |
} | |
}); | |
}); | |
app.listen(3000, () => { | |
console.log('Server is running on port 3000'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment