First of all you have to install multer package in your system and then paste text below typed:
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, path.resolve('public') + '/images/uploads/')
},
filename: function (req, file, cb) {
cb(null, Date.now() + path.extname(file.originalname))
}
});
Storage variables contains the destination of file upload and filename is the access to change file name if you want , i am changing the filename with current date.
next it
var upload = multer({
dest: path.resolve('public') + '/images/uploads/',
limits: {
fileSize: 3 * 1024 * 1024,
files: 20
},
storage: storage,
rename: function (fieldname, filename) {
return fieldname+"_"+Date.now();
},
onFileUploadStart: function (file) {
console.log(file.originalname + ' is starting to upload');
},
onFileUploadComplete: function (file) {
console.log(file.originalname + ' uploaded to ' + file.path);
}
});
paste this code group and write post api and incude upload varialbe to store image to the destination
.
like
;
router.post('/imageUpload', function(req,res,next)
{
upload(req,res,function(err){
/* for single image*/
req.file.filename // filename is the image name stored in database
/* for multiple images*/
req.files.filename
});
});