Sunday 29 October 2017

How do you make multer save the file in a folder?

I'm having trouble using multer to save a photo in a folder. The path of the file would be uploaded to mlab (working fine), but its supposed to grab the image from the folder I want it to grab it from, which is just not saving. When trying to look at it from the view, it throws a 404 error, due to the picture not being present in the folder. Here's my server-side controller:var multer = require('multer'); var storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, './modules/articles/client/img/'); // where to store it }, filename: function (req, file, cb) { if(!file.originalname.match(/\.(png|jpg|jpeg|pdf|gif)$/)) { //console.log("filename error"); var err = new Error(); err.code = 'filetype'; // to check on file type return cb(err); } else { //console.log("produced filename"); var day = new Date(); var d = day.getDay(); var h = day.getHours(); var fileNamee = d + '_' + h + '_' + file.originalname; console.log("filename produced is: " + fileNamee); cb(null, fileNamee); } } }); var upload = multer({ storage: storage, limits: { fileSize: 20971520 } // Max file size: 20MB }).single('myfile'); // name in form exports.uploads = function (req, res) { //console.log("in uploads"); upload(req, res, function (err) { if (err) { if (err.code === 'LIMIT_FILE_SIZE') { res.json({ success: false, message: 'File size is too large. Max limit is 20MB' }); } else if (err.code === 'filetype') { res.json({ success: false, message: 'File type is invalid. Accepted types are .png/.jpg/.jpeg/.pdf' }); } else { console.log('err = ' + err); res.json({ success: false, message: 'File was not able to be uploaded' }); } } else { if (!req.file) { //console.log("reached here with !rep.file"); var article = new Article(req.body); article.user = req.user; article.save(function (err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(article); } }); } else if (req.file) { //console.log("reached here with req.file"); res.json({ success: true, message: 'File was uploaded!' }); } } // Everything went fine }); }; The img folder has chmod 755 whereas the server-side controller has chmod 644 (-rw-r--r--). I will say that if I throw print statements in the middle of the exports.upload functions and the filename function, nothing prints out. Does it have to do something with not being called? I'm kinda new working to MeanJS

Submitted October 29, 2017 at 06:31PM by AndroidGuru7

No comments:

Post a Comment