Search code examples
node.jsexpressmulter

How to return id of uploaded file (upload with multer in nodejs express app)


I have an MEAN stack app and trying to upload file with multer. Upload is working fine the only problem is I want to return uploaded file's id.

//multer settings for single upload
var upload = multer({ storage: storage }).single('file');

app.post('/upload', upload, function (req, res) {
//// ????? What to return and how? 
});

I'm subscribed to this post into angular2 service. Thank you for help.


Solution

  • var multer = require('multer');
    
    // storage for upload file.
     var storage  = multer.diskStorage({
         destination: function (req, file, callback) {
         callback(null, './file');
      },
      filename: function (req, file, callback) {
         callback(null, file.originalname);
      }
     });
    
     var Upload = multer({
        storage: storage 
     }).any('file');
    
    
     router.post('/upload', postData);
    
    function postData(req, res) {
     Upload(req, res, function (error) {
        if (error) {
            res.status(400).send(error);
        }
        var obj = {};
        obj.file = req.files.filename;
        //file is getting stored into database and after it successfully stored 
        //into database it will return you Id
        db.create(obj, function (err, data) {
                            if (err) {
                                res.send('error');
                            }
                            if (!data) {
                                res.send('Error');
                            } else {
                                console.log('file upload');
                                res.send(data._id);
                            }
                        });
                });
           }
    

    to return Id you should have to store reference somewhere in database and after that you will return id to Angular2