【问题标题】:Express file upload with multer, but not as middleware使用 multer 快速上传文件,但不能作为中间件
【发布时间】:2018-03-29 21:54:53
【问题描述】:

我想在我的快速路由块中使用 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

有什么想法吗?

【问题讨论】:

    标签: express file-upload multer


    【解决方案1】:

    通过将我的控件移动到中间件以在 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();
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-06
      • 2016-04-11
      • 1970-01-01
      • 1970-01-01
      • 2023-02-21
      • 2018-02-25
      • 2020-03-13
      相关资源
      最近更新 更多