How to set different destinations in nodejs using multer?

后端 未结 5 1852
你的背包
你的背包 2021-01-31 22:11

I\'m trying to upload any file using Multer package. It\'s working fine when I use following code in my server.js file.

var express         


        
5条回答
  •  既然无缘
    2021-01-31 22:28

    You can make a function like so:

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

    And then use it in your upload route:

    //Handle the library upload
        app.post('/app/library/upload', isAuthenticated, function (req, res) {
            var currUpload = uploadFnct('library');
            currUpload(req,res,function(err){
                if(err){
                     res.json({error_code:1,err_desc:err});
                     return;
                }
                res.json({error_code:0,err_desc:null, filename: req.file.filename});
            });
        });
    

提交回复
热议问题