【问题标题】:Express Multer validate request before uploading file上传文件前 Express Multer 验证请求
【发布时间】:2021-02-19 01:18:03
【问题描述】:

我目前正在使用 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.js express multer multer-s3


    【解决方案1】:

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

    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;
    
      });
    

    【讨论】:

      【解决方案2】:

      只是用于验证的另一层。您可以使用 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);  
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-08-19
        • 2019-07-04
        • 2017-03-01
        • 1970-01-01
        • 2014-07-14
        • 1970-01-01
        • 2022-08-03
        相关资源
        最近更新 更多