routes.js
module.exports=function(app, upload){
var postingsController=require('../controllers/postings.server.controller');
app.post('/postings', postingsController.savePosting);
}
controller.js
var multer=require('multer');
exports.savePosting=function(req, res, next){
// this diskstorage function is not at all executed
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads')
},
filename: function (req, file, cb) {
console.log(file);
cb(null, file.filename + '.' + 'jpg');
}
});
var upload = multer({ storage: storage });
upload.single('attachment');
res.json({ message: "success" });
}
有人可以告诉我哪一行准确上传文件。我是在主快捷配置文件中编写multer diskstorage配置还是可以在任何地方写入。顺便说一下,我能看到来自线路的json响应
答案 0 :(得分:1)
通常,创建中间件并将其插入任何实际路由处理程序之外。例如:
<强> routes.js 强>
var multer = require('multer');
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads')
},
filename: function (req, file, cb) {
console.log(file);
cb(null, file.filename + '.' + 'jpg');
}
});
var upload = multer({ storage: storage });
module.exports = function(app, upload) {
var postingsController = require('../controllers/postings.server.controller');
app.post('/postings',
upload.single('attachment'),
postingsController.savePosting);
};
<强> controller.js 强>
exports.savePosting = function(req, res, next) {
// Use `req.file` to access attachment
if (req.file)
res.json({ message: "success" });
else // no file uploaded
res.json({ message: "failure" });
};
答案 1 :(得分:0)
Multer是一个中间件,这意味着它在大多数情况下都会作为参数添加到您的路线中。那么实际的语法是什么:
app.post ("/postings", multer ({ ... }), postingsController.savePosting);
Multer被要求在&#34; / posts&#34;以及为您完成所有文件工作的最终功能。然后它将通过
为您提供所有信息
req.files["fileInputName"]
在以下中间件中(您的功能是&#34;中间件&#34;也是)。