maria maria - 2 months ago 32
Node.js Question

node multer return new file name

How can i make the multer return the new filename (

superfilename
) for the file beeing uploaded?

so when complete, it would return the new filename as well?

server sided:

var storage = multer.diskStorage({ //multers disk storage settings
destination: function (req, file, cb) {
cb(null, '/opt/mean/public/uploads/')
},
filename: function (req, file, cb) {
var datetimestamp = Date.now();
var superfilename = file.fieldname + '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length -1];
cb(null, superfilename)
}
});
var upload = multer({ //multer settings
storage: storage
}).single('file');



upload(req,res,function(err){

if(err){
res.json({error_code:1,err_desc:err});
return;
}
res.json({error_code:0,err_desc:null});
});

Answer

you can retrun destination file name: req.file.filename

One way is pass the upload object as a middleware for your upload route as below. Rest file related information will be in your request object. You can refer to the official documentation for exposed api's

app.post('/uploadFile',upload,(req,res)=>{

      if(req.file !==  undefined){

        // once uploaded save the user data along with uploaded photo path to the database.
        res.json({
           'fileName':req.file.originalname,
           'destination':req.file.filename,
           'userName':req.body.userName,
           'phoneNumer':req.body.phoneNumber
        });
      }else{
        res.json({
          'message':'Unable to Upload file'
        });
      }
  });
Comments