mo30
mo30

Reputation: 89

expressjs - how to require multer in another file

i use according to it's readme file in github
it's readme said call multer in like this:

app.js

var multer = require('multer')
app.post('/upload', upload.single('image'), function(req, res){})

but i defined my function(req, res) in another file - post.js - and my code in app.js looks like this:

app.post('/upload', upload.single('image'), post.new)

how can i require multer only on post.js, almost like this:

post.js

 var multer = require('multer')
 module.exports.new = function(req, res){
     //access to req.file
 }

app.js

 app.post('/upload', post.new)

Upvotes: 1

Views: 1881

Answers (2)

Sagar
Sagar

Reputation: 1424

For MVC structure You can simply do this by :

function Uploader(req, res, next) {
    var storage = multer.diskStorage({
        destination: function (req, file, cb) {

            cb(null, your_path);

        },
        filename: function (req, file, cb) {
            cb(null, filename)
        }
    });

    var upload = multer({
        storage: storage
    });

    return upload;
}

module.exports = Uploader

In another file you can simply use

app.post('/upload', Uploader.single('image'), function(req, res){})

If you don't want to create function, you can do the following:

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, upload_filePath)
  },
  filename: function (req, file, cb) {
        cb(null,filename)
  }
})
var upload= multer({
   storage : upload
})

module.exports.upload=upload;

Both gives same result but using Function is more appropriate way.

Upvotes: 2

skirtle
skirtle

Reputation: 29092

I can think of two ways.

Firstly, you could expose new as an array:

module.exports.new = [upload.single('image'), function(req, res) {
    ...
}];

Secondly, you could use multer within your function:

var imageUpload = upload.single('image');

module.exports.new = function(req, res) {
    imageUpload(req, res, function(err) {
        // Put the rest of your code here
    });
};

In this second approach we're just invoking the multer middleware function ourselves, passing it our own function to use as the next callback. There's a little bit more information about doing this at https://github.com/expressjs/multer#error-handling though it describes the technique in a slightly different context.

Upvotes: 2

Related Questions