I am trying to rename an image file uploaded with multer by the request parameters.
Here is my code:
router.route('/upload/:userid')
.post(multer({
dest: 'uploads/'
}), function(req,res){
fs.readFile('uploads/' + req.files.file.name, function(err, data) {
fs.writeFile('uploads/' + req.params.userid + '.' + req.files.file.extension, data, function(err) {
fs.unlink('uploads/' + req.files.file.name, function(){
if(err) throw err;
});
});
});
res.json({ message: 'Successfully uploaded image!' });
});
It works great but I was wondering if it exists something cleaner and easier with multer rename function.
It already tried something like this:
router.route('/upload/:userid')
.post(multer({
dest: 'uploads/',
rename: function(req,res) {
return req.params.userid
}
}), function(req,res){
res.json({ message: 'Successfully uploaded image!' });
});
But it does not work because req is not populated yet (undefined).
I use httpie to test my code with the following command:
http.exe -f POST http://localhost:8080/upload/171284 file@D:\....\cat.jpg
Is it possible to use rename function of multer to do what I do with fs? Or is there a better way?
Thank you for your feedbacks.
Thomas
EDIT
My new code using diskStorage:
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/')
},
filename: function (req, file, cb) {
cb(null, req.params.userid + '-')
}
})
var upload = multer({ storage: storage })
router.route('/upload/:userid')
.post(multer({
storage: storage
}), function(req,res){
res.json({ message: 'Successfully uploaded image!' });
});
That throws an error:
Error: Route.post() requires callback functions but got a [object Object]