我在express中使用multer进行文件存储,但是当我在文件中使用req.params.event时,我得到了undefined。为什么会这样呢?没有req.params.event我无法将我的上传文件分类到文件夹
var multer = require('multer');
var storage = multer.diskStorage({
destination: function (req, file, callback) {
console.log(req.params.event); //This console log is undefined
callback(null, './uploads');
},
filename: function (req, file, callback) {
callback(null, file.fieldname + '-' + Date.now());
}
});
var upload= multer({
storage: storage
}).single('userPhoto');
module.exports={upload:upload};
这是我的活动路线
app.get('/events/:event', (req, res) => {
console.log(req.params.event); // here working perfectly
res.render('event.hbs', {
});
})
这是上传路线
app.post('/events/upload',upload,function(req,res){
console.log("uploded")
});
甚至req.params在multer中都是空的
答案 0 :(得分:1)
Quit late for this answer, but maybe it will help to someone
使用multer上传文件时,参数和请求对象的查询不会在文件之前填充,因此您无法在文件上传之前访问它,就像multer.diskStorage下的情况一样。 < / p>
相似请求正文可能未在文件上传之前完全填充。这取决于客户端将字段和文件传输到服务器的顺序。
您可以在此处查看req.body:
https://github.com/expressjs/multer#diskstorage
立即回答,使用multer将文件保存在其他文件夹下:
1)首先,您应该使用req.body.event对文件夹进行分类,即使用主体而不是通过使用查询和参数来传递事件
2)现在,在从客户端发布文件的过程中,反转事件和文件的顺序,即先发布事件,然后发布文件
您可能会参考对我来说效果很好的这段代码
const fileStorage = multer.diskStorage({
destination: (req, file, cb) => {
if (req.body.event == 'test') {
cb(null, "images/test"); // it will upload inside test under images
} else {
cb(null, "images/try"); // it will upload inside try under images
}
},
filename: (req, file, cb) => {
cb(null, new Date().toISOString() + "-" + file.originalname);
}
});
现在从客户端说使用邮递员:
如您在图像中所见,事件键位于图像键之前
现在它将检测到身体,并能够将文件上传到不同的文件夹中,并按照示例代码进行尝试。