Skip to content

Instantly share code, notes, and snippets.

@sujaykundu777
Created August 28, 2020 08:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sujaykundu777/de4cbf52526440b1227842631c7aee32 to your computer and use it in GitHub Desktop.
Save sujaykundu777/de4cbf52526440b1227842631c7aee32 to your computer and use it in GitHub Desktop.
File Upload Multer Node API
import express from 'express';
import multer from 'multer';
import Image from './../models/upload.model';
const router = express.Router();
// multer local storage
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads');
},
filename: function (req, file, cb) {
cb(null, Date.now() + file.originalname);
}
});
// filter uploaded files (allowed: jpeg, png)
const fileFilter = (req, file, cb) => {
if(file.mimetype === 'image/jpeg' || file.mimetype === 'image/png' || file.mimetype === 'image/jpg'){
cb(null, true);
}else{
// rejects storing the file
cb(null, false);
}
}
// upload
const upload = multer({
storage: storage,
limits: {
fileSize: 1024 * 1024 * 5
},
fileFilter : fileFilter
});
const newImage = new Image({
imageName: req.body.imageName,
imageData: req.file.path
});
newImage.save()
.then((result) => {
res.status(200).json({
success: true,
document: result
});
})
.catch((err) => next(err));
});
module.exports = router;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment