0
我在使用multer將照片保存到文件夾時遇到問題。文件的路徑將被上傳到mlab(工作正常),但它應該從我想從它抓取它的文件夾中抓取圖像,這只是不保存。當試圖從視圖中查看它時,由於圖片不存在於文件夾中,它會引發404錯誤。這裏是我的服務器端控制器:你如何讓multer將文件保存在一個文件夾中?
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
});
};
對不起,我有點新來處理meanJS和客戶端 - 服務器工作,但img文件夾有chmod 755,而服務器端控制器有chmod 644(-rw-r - r--)。我會說,如果我在exports.upload函數和文件名函數中間引入print語句,則不會打印出任何內容。它是否需要做一些事情而不被稱爲? – Andrei