Reputation: 1248
I am using multer for file storage in express, however when i use req.params.event in the file i get undefined. Why is this happening. Without req.params.event i cant categorize my uploads in folder
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};
This is my route for the event
app.get('/events/:event', (req, res) => {
console.log(req.params.event); // here working perfectly
res.render('event.hbs', {
});
})
This is upload route
app.post('/events/upload',upload,function(req,res){
console.log("uploded")
});
Even req.params is empty in multer
Upvotes: 3
Views: 4297
Reputation: 3031
Quit late for this answer, but maybe it will help to someone
When using multer for uploading file, params and query of request object does not populated before file, so you can not access it before uploading of file, as in your case under multer.diskStorage.
similary req.body may not have been fully populated before uploading of file. It depends on the order that the client transmits fields and files to the server.
you can check here for req.body :
https://github.com/expressjs/multer#diskstorage
Now Answer to save files under different folder using multer :
1) First of all you should use req.body.event to categorize folders, i.e transmit event using body not by using query and params
2) Now during posting of file from client side reverse the order of event and file, i.e post event first then file
You may refer to this code that is working well for me
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);
}
});
Now from client side say using postman:
As you can see in image, event key is placed before image key
Now it will detect body and will able to upload files into different folders test and try as in example code.
Upvotes: 7