Alireza Valizade Alireza Valizade - 1 month ago 4
Ajax Question

how to access to filename in my requst block in multer

I Need Access to file name in my request body because i want store in my db but i dont know handle that , this is my code :

var storage = multer.diskStorage({
destination: function (req, file, callback) {
var name = 'public/images/' + Math.floor((Math.random() * 10675712320) + 1);
fs.mkdir(name, (err)=> {
if (err) {
console.log(err);
} else {
** Im want pass name variable**
callback(null, name);
}
});
},
filename: function (req, file, callback) {
callback(null, file.originalname);
}
});
var upload = multer({storage: storage}).single('userPhoto');

app.post('/api/photo', function (req, res) {
***upload(req, res, function (data) {
I need access to file name here because i want store in my db***
console.log(data);

res.end("File is uploaded");
});
});


Im try this way but not working :

fs.mkdir(name, (err)=> {
if (err) {
console.log(err);
} else {
callback(name, name);
}
});

Answer

you can access to path from req.file.path like this :

var upload = multer({storage: storage}).single('userPhoto');

app.post('/api/photo', function (req, res) {
    upload(req, res, function (data) {
        console.log(req.file.path);
        res.end("File is uploaded");
    });
});