我无法使用multer将照片保存在文件夹中。该文件的路径将上传到mlab(工作正常),但它应该从我希望它从中获取的文件夹中抓取图像,这只是不保存。当试图从视图中查看它时,由于图片中没有图片,它会抛出404错误。这是我的服务器端控制器:
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)$/)) {
var err = new Error();
err.code = 'filetype'; // to check on file type
return cb(err);
} else {
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) {
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) {
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) {
res.json({ success: true, message: 'File was uploaded!' });
}
}
// Everything went fine
});
};
答案 0 :(得分:0)
代码运行正常。检查文件夹权限。确保服务器能够写入文件夹。