上载文件之前,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,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之前,如何验证请求对象。

解决方法

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

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;

  });
,

只是另一个验证层。您可以使用 Joi 来验证您的请求。在保存您的数据之前。

//router.ts
router.post('/',Upload.single('image'),ProductController.create);

//controller.ts
export const create = async(req:Request,res:Response) => {

   const image = (req.file as any).location;
   const body = { ...req.body,image: image }

   const { error } = validate(body);
   if (error) return res.status(400).send(error.details[0].message);

   const product = await ProductService.create(body);

   res.status(201).send(product); 
}

//product.ts 
function validateProduct(product : object) {
  const schema = Joi.object({
      name: Joi.string().min(5).max(50).required(),brand: Joi.string().min(5).max(50).required(),image: Joi.string().required(),price: Joi.number().required(),quantity:Joi.number(),description: Joi.string(),});

  return schema.validate(product);  
}