Reputation: 765
I am trying to upload file to specific directory in the disk. I am using multer library. And as far as i understand this code and how it looks like now when it gets a request it takes file from it and tries to save it and it happens separately from the rest of the request. Is there a way to gain acces to full requst in let's say destination function(#1). Here is my code
var storage = multer.diskStorage({
destination: function (req, file, callback) {
console.log(req) // #1 here i dont see other fields from request
callback(null, './uploads')
},
filename: function (req, file, callback) {
callback(null, Date.now() + '-' + file.originalname)
}
})
var upload = multer({ storage: storage }).single('file')
router.post('/api/photos', function (req, res, next) {
upload(req, res, function(err) {
console.log(req) // here i see other fields from request like req.body.description
if (err) {return next(err)}
res.json(201)
})
});
What i would like to actually do is to say multer. 'Hey i want you to save file in directory /uploads/restOfThePat'. Where restOfThePath is passed in the request.
I know that i can change file location later(didnt tried this, dont know if it works). However it seems kinda hacky and i cant believe it is not possible any other cleaner way. Obviously multer is not a must, if there is some other library i would like to take a look.
Upvotes: 0
Views: 1362
Reputation: 2490
You can do this:
var storage = multer.diskStorage({
destination: function (req, file, callback) {
console.log(req);
callback(null, req.body.what_you_want);
},
filename: function (req, file, callback) {
callback(null, Date.now() + '-' + file.originalname);
}
})
var upload = multer({ storage: storage });
router.post('/api/photos', upload.single('the_name') function (req, res, next) {
upload(req, res, function(err) {
console.log(req) // here i see other fields from request like req.body.description
if (err) {return next(err)}
res.json(201)
})
});
It works like a charm…
Upvotes: 1