Set multer properties inside an express route

1k views Asked by At

Instead of attaching multer to the entire express app, i am trying to include it just for specific routes, which is better since you will be preventing uploads to every route handling post.

Problem is, i am unable to set it properties inside a route.

var router = require('express').Router(),
multer = require('multer');

router.post('/uploads', function (req, res, next) {
   multer({
     dest: req.app.get('cfg').uploads.dir
   });

   console.log(req.files); process.exit();

});

Here, req.files is undefined.

The same thing happens if i put multer in a seperate middleware and attach it to the above route.

function initMulter(req, res, next) {
    multer({
     dest: req.app.get('cfg').uploads.dir
   });

   next();
}

 router.post('/uploads', initMulter, function (req, res, next) {
   console.log(req.files); process.exit();

});

Also in this case, req.files is undefined.

Is there something really wrong that i am doing or should i start blaming the beer?

1

There are 1 answers

3
Ben Fortune On BEST ANSWER

Multer is it's own middleware.

You can add it to a route via:

router.post('/uploads', multer({
     dest: './my/destination' //req.app.get('cfg').uploads.dir
}), function (req, res, next) {
    console.log(req.files);
    process.exit();
});

Though you're going to have to find another way to access your config.

One way would be to pass the config or app through an export function.

module.exports = function(config) {
    router.post('/uploads', multer({
         dest: config.uploads.dir
    }), function (req, res, next) {
        console.log(req.files);
        process.exit();
    });
    return router;
});

Then when you're requiring,

var route = require('./route')(app.get('cfg'));