Nodejs Express 4 Multer | Stop file upload if user not authorized

后端 未结 3 898
南旧
南旧 2021-02-09 01:29

I\'m using multer as multipart middelware for express4.

Express is configured to use passport as auth middelware, but I cannot find a way to prevent file up

3条回答
  •  生来不讨喜
    2021-02-09 02:02

    EDIT

    I'll leave the answer below in case it helps, but the answer is actually quite simple: you need to move the two calls to app.use(passport) above the call to app.use(multer). Each step in the express chain is processed in order, so if you wish reject a bad auth attempt, do it before you handle the incoming file upload.


    There is probably a better way to do this, but this should get you started. Change your express config to use a closure and you'll have full access to the req variable.

    app.use(function(req, res, next) {
      var handler = multer({
        dest: wwwroot + path.sep + 'uploaded' + path.sep, 
        onFileUploadStart: function (file) {
          // You now have access to req
          console.dir(req);
          console.log(file.fieldname + ' is starting ...')
        },
        onFileUploadComplete: function (file) {
          console.log(file.fieldname + ' uploaded to  ' + file.path)
        }
      });
      handler(req, res, next);
    });
    

提交回复
热议问题