I'm new to Node.js and I ran into a simple problem lately.
I'm using multer
module to upload images.
In my web app all the users have a unique id, and I want the uploaded images to be stored in a directory to be named based on their id.
Example:
.public/uploads/3454367856437534
Here is a part of my routes.js
file:
// load multer to handle image uploads
var multer = require('multer');
var saveDir = multer({
dest: './public/uploads/' + req.user._id, //error, we can not access this id from here
onFileUploadStart: function (file) {
return utils.validateImage(file); //validates the image file type
}
});
module.exports = function(app, passport) {
app.post('/', saveDir, function(req, res) {
id : req.user._id, //here i can access the user id
});
});
}
How can I access req.user._id
attribute outside the callback function(req, res)
,
so I can use it with multer
, to generate the proper directory based on the id?
EDIT Here is what I have tried and didn't work:
module.exports = function(app, passport) {
app.post('/', function(req, res) {
app.use(multer({
dest: './public/uploads/' + req.user._id
}));
});
}