Created
August 28, 2020 08:05
-
-
Save sujaykundu777/de4cbf52526440b1227842631c7aee32 to your computer and use it in GitHub Desktop.
File Upload Multer Node API
This file contains 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
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