How do I get current user session when I upload/save a file using multer?

712 Views Asked by At

I have the file upload working and saving properly. My current problem is that I need the file name to contain a user ID or username so I can keep files separate for each user. Heres my current setup

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'myuploadpath')
  },
  filename: function (req, file, cb) {
    console.log(req);
    cb(null, + file.originalname)
  }
})

var upload = multer({ storage: storage });  

Here is the api call

router.post('/signup', upload.single("resume"), function(req, res) {
    console.log("file:" + req.file);

    var user = {
        username: req.body.username,
        email: req.body.email,
        password: req.body.password,
        f_name: req.body.f_name,
        l_name: req.body.l_name,
        city: req.body.city,
        state: req.body.state,
        zip: req.body.zip
    };
    connection.query('INSERT INTO user SET ?', user, function(err, result) {
        if (err)
            throw err;
        res.redirect('/login');
    });

});  

I am also creating a user here but I will have a profile page too that they will be able to add a different file.

I was trying to call req.body.username in the filename function but it returns "NaN". Any tips on how to get the username or id before naming the file?

0

There are 0 best solutions below