frustrated-dev
frustrated-dev

Reputation: 451

How to get input filename in multer with node.js

How can we get the name of the file that we are inputed when uploading files? I using multer on node.js and I want to store the filename in mysql db but I can't figure out how to get the filename.

var cpUpload = upload.fields([{ name: 'featured_img', maxCount: 1 }, { name: 'audio', maxCount: 1 }]);
app.post('/save', cpUpload, function (req, res, next) { 
    let data = {featured_img: req.files.featured_img, title: req.body.title, band_name: req.body.band_name, audio: req.files.audio};
    let sql = "INSERT INTO music SET ?";
    let query = connection.query(sql, data,(err, results) => {
      if(err) throw err;
      console.log(data);
      res.redirect('/');
    });
});

enter image description here enter image description here

Upvotes: 0

Views: 364

Answers (1)

Karl L
Karl L

Reputation: 1725

You've missed to go a couple of level deeper. As req.files.featured_img is the object data. you need to access the property filename. also consider that it is in an ARRAY, so you need to access [0] as well. Same goes with the audio

So it would be like this:

let data = {
             featured_img: req.files.featured_img[0].filename, 
             title: req.body.title, 
             band_name: req.body.band_name, 
             audio: req.files.audio[0].filename
            };

Just incase you need the location or the URL path as well, just do req.files.featured_img[0].path and req.files.audio[0].path

Upvotes: 2

Related Questions