minisaurus
minisaurus

Reputation: 1196

Express file upload with multer, but not as middleware

I'd like to use multer in my express route block, i.e. not as middleware. The multer config I have works as middleware, but I want to have a couple of checks before calling multer.

So I've tried this, to no avail:

/*
 * Upload a file
 */
const MediaPath = "/var/tmp";
var multer  = require('multer'); // Multer is for file uploading
var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, MediaPath  + '/' + req.params.organisation + '/' + req.params.table + '/');
  },
  filename: function (req, file, cb) {
    // TODO - remove the time and timezone from ISO string, resolve the correct filename, create thumbnail, 
    var date = new Date();
    cb(null, req.params.id + '.' + date.toISOString());
  }
})
//var upload = multer({ storage: storage });
var upload = multer({ storage: storage }).single('file');

router.post('/file/:organisation/:table/:id', function (req, res, next){
   db.resolveTableName( req )
  .then( table => {
    auth.authMethodTable( req )
    .then( function() {
console.log('Uploading a file: ');
        upload(req, res, function( err ) {
          if( err ) {
console.log('Upload error' );
            res.status(500).json( err );
          }
console.log('Upload success' );
          res.status(200).json("success");
        });
    })
    .catch( function( error ) {
      res.status(401).json('Unauthorized');
    });
  })
  .catch( function(e) {
    res.status(400).json('Bad request');
  });
});

Funnily I get no error, so 200 is returned, but I get no uploaded file.

I took that pattern from here: https://www.ibm.com/developerworks/community/blogs/a509d54d-d354-451f-a0dd-89a2e717c10b/entry/How_to_upload_a_file_using_Node_js_Express_and_Multer?lang=en

Any ideas?

Upvotes: 1

Views: 2332

Answers (1)

minisaurus
minisaurus

Reputation: 1196

Fixed it by moving my controls to a middleware to call before multer, so I can use multer as middleware (inspired by this comment Nodejs Express 4 Multer | Stop file upload if user not authorized):

var preUpload = function( req, res, next ) {
   db.resolveTableName( req )
  .then( table => {
    auth.authMethodTable( req )
    .then( function() {
         next();
    })
    .catch( function( error ) {
      res.status(401).json('Unauthorized');
    });
  })
  .catch( function(e) {
    res.status(400).json('Bad request');
  });
};

router.post('/file/:organisation/:table/:id', preUpload, upload.single('file'), function (req, res, next){
  console.log(req.body, 'Body');
  console.log(req.file, 'files');
  res.end();
});

Upvotes: 3

Related Questions