如何使用NodeJS处理异步上传文件?

时间:2017-12-29 07:37:16

标签: javascript node.js asynchronous upload multer

我使用Multer来管理文件上传。我必须与JWT(this.verify)核实以确认此帖子。如果是success则我的文件已上传。因为我的代码是异步的,所以我无法调用this.configUpload()

这是路由器:

const mailer = require('../../libraries/mailer_lib');
router.post('/',mailer.configUpload(),mailer.verifyJWT());

我的Mailer_lib:

const Mailer = function() {
  this.configUpload = function() {
    const path_folder = '../../uploads/';
    var storageOptions  = multer.diskStorage({
      destination: function (req, file, cb) {
        let dest = path.join(__dirname, path_folder) ;
        cb(null, dest);
      },
      filename: function (req, file, cb) {
        let nameFilter = common.sanitizeFileName(file.originalname);
        var hashName = md5(nameFilter + common.getTimeMSFloat());
        cb(null, hashName + path.extname(file.originalname));
      }
    });
    const multipartMiddleware = multer({
      storage : storageOptions,
      fileFilter: function (req, file, callback) {
        var isFile = file.originalname.toLowerCase();
        if (!isFile.match(/ \.(jpg | jpeg | png | doc | docx | xls | xlsx | zip | pdf | ppt | pptx)$ / )) {
          return callback(new Error('Format File Not Allowed'), false);
        }
        callback(null, true);
      },
      limits: { // 6MB
        fileSize: 1024000 * 6
      },
      inMemory: true,
      includeEmptyFields: true
    });

    var cpUpload = multipartMiddleware.fields([
    { name: 'proofReporting', maxCount: 1}
    ]);
    return cpUpload;
  };
  this.verifyJWT = function () {
    return function(req, res) {
      var app = req.app;
      var DB = req.DB;
      var token = req.body.token || req.query.token || req.headers['x-access-token'] || req.headers.authorization || req.params.token;
      var secret = process.env.SECRET_KEY_JWT;
      if (token) {
        jwt.verify(token, secret, function(err, decoded) {
          if (err) {
            logger.error('JWT_ERROR', err.message);
            res.json({
              'responseStatus': {
                'responseCode' : 403,
                'responseDesc': err.message
              }
            });
          } else if (!decoded.reminder_id) {
            logger.info('Your Token is not for confirmation reminder');
            res.json({
              'responseStatus': {
                'responseCode' : 403,
              'responseDesc': 'Your Token is not for confirmation reminder'
              }
            });
          } else if (decoded.next_schedule <= common.today().substring(0, 10)) {
            logger.info(`Reminder with ID $ {decoded.reminder_id} Expired`);
            res.json({
              'responseStatus': {
                'responseCode' : 403,
              'responseDesc': 'This Reminder has expired'
              }
            });
          } else {
            DB.query(`SELECT is_confirm, date_checked FROM reminder WHERE reminder_id = $ {decoded.reminder_id} `, { type: DB.QueryTypes.SELECT})
            .then(status => {
              if (status[0].is_confirm == 0) { // pending / not approve /
                var reminderModel = createModel(app);
                reminderModel.update({
                  isConfirm : 1,
                  confirmBy : decoded.user_id,
                  dateChecked : common.today()
                }, {
                  where : {
                    reminderId : decoded.reminder_id
                  }
                })
                .then(row => {
                  if (row == 1) {
                    logger.info('Approve');
                    res.json({
                      responseStatus : {
                        responseCode : '00',
                        responseDesc : 'Reminder Has Approve',
                      }
                    });
                  } else {
                    logger.info('Not Approve');
                    res.json({
                      responseStatus : {
                        responseCode : 400,
                        responseDesc : 'Bad request',
                      }
                    });
                  }
                })
                .catch(err => {
                  logger.error('SQL_GET_EMAIL', err);
                  res.json({
                    responseStatus : {
                      responseCode : 500,
                      responseMessage : 'Internal Server Error'
                    }
                  });
                });
              } else if (status[0].is_confirm == 1) {
                logger.info('Reminder Has Approve');
                res.json({
                  responseStatus : {
                    responseCode : '00',
                    responseDesc : 'Reminder Has Approve',
                    responseDetail : ` ${status[0].date_checked}`
                  }
                });
              }
            })
            .catch(err => {
              logger.error('SQL Query', err);
              res.json({
                responseStatus : {
                  responseCode : 500,
                  responseMessage : 'Internal Server Error'
                }
              });
            });
          }
        });
      } else {
        logger.error('TOKEN', 'No token provided');
        res.json({
          responseStatus : {
            responseCode : 403,
            responseMessage : 'No token provided'
          }
        });
      }
    };
  };
};

我改为:

const mailer = require('../../libraries/mailer_lib');
router.post('/'mailer.verifyJWT());

并将mailer.configUpload放在后面 - &gt; mailer.verify()但我的文件未上传。

0 个答案:

没有答案