使用multer上传文件,但不作为中间件

时间:2018-03-29 11:49:23

标签: express file-upload multer

我想在我的快速路线块中使用multer,即不是作为中间件。 multer配置我作为中间件工作,但我想在调用multer之前进行一些检查。

所以我试过这个,但无济于事:

/*
 * 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');
  });
});

有趣的是我没有收到错误,所以返回了200,但我没有上传文件。

我从这里采取了这种模式: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

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

通过将我的控件移动到中间件以在multer之前调用来修复它,因此我可以使用multer作为中间件(受此评论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();
});