首页 > 解决方案 > 上传文件前 Express Multer 验证请求

问题描述

我目前正在使用 multer-s3 ( https://www.npmjs.com/package/multer-s3 ) 将单个 csv 文件上传到 S3,我让它以这种方式工作:

var multer = require('multer');
var multerS3 = require('multer-s3');
var AWS = require('aws-sdk');

AWS.config.loadFromPath(...);
var s3 = new AWS.S3(...);

var upload = multer({
  storage: multerS3({
    s3: s3,
    bucket: 'my-bucket',
    metadata: function (req, file, cb) {
      cb(null, {fieldName: file.fieldname});
    },
    key: function (req, file, cb) {
      cb(null, Date.now().toString())
    }
  })
});

然后它的路由是这样的:

app.route('/s3upload')
  .post(upload.single('data'), function(req, res) {

    // at this point the file is already uploaded to S3 
    // and I need to validate the token in the request.

    let s3Key = req.file.key;

  });

我的问题是,如何在 Multer 将我的文件上传到 S3 之前验证请求对象。

标签: node.jsexpressmultermulter-s3

解决方案


您可以在上传之前再链接一个中间件,然后可以在那里检查令牌

function checkToken(req, res) {
    // Logic to validate token
}

app.route('/s3upload')
  .post(checkToken, upload.single('data'), function(req, res) {

    // at this point the file is already uploaded to S3 
    // and I need to validate the token in the request.

    let s3Key = req.file.key;

  });

推荐阅读