最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Multer validation with joi - Stack Overflow

programmeradmin2浏览0评论

I've created an endpoint to post and upload a csv file for processing in Node. It works fine but I'm trying to figure out how to validate a few things before uploading the file.

A sample request would be:

{
    "test_doc": "/path/to/file/test.csv"
    "offset": [0,1]
}

I want the form to require "test_doc" and only accept csv files and have "offset" be optional

The schema for the "offset" works but I'm unsure how to validate the file with multer as well, especially before uploading it.

Sample code below

const upload = multer({ dest: "/tmp" });

router.post("/", upload.single("test_doc"), async (req, res) => {
    const schema = joi.object().keys({
        offset: joi.array().items(joi.number().min(-60).max(60)).min(1).max(2)
    });
});

I've created an endpoint to post and upload a csv file for processing in Node. It works fine but I'm trying to figure out how to validate a few things before uploading the file.

A sample request would be:

{
    "test_doc": "/path/to/file/test.csv"
    "offset": [0,1]
}

I want the form to require "test_doc" and only accept csv files and have "offset" be optional

The schema for the "offset" works but I'm unsure how to validate the file with multer as well, especially before uploading it.

Sample code below

const upload = multer({ dest: "/tmp" });

router.post("/", upload.single("test_doc"), async (req, res) => {
    const schema = joi.object().keys({
        offset: joi.array().items(joi.number().min(-60).max(60)).min(1).max(2)
    });
});
Share Improve this question asked Apr 22, 2020 at 0:55 Supez38Supez38 3492 gold badges4 silver badges17 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 2

You can use the fileFilter method to validate file types in Multer. The fileFilter method is a built-in method which es with Multer middleware:

const upload = multer({
    dest: "/tmp",
    fileFilter: (req, file, cb) => {
      if (file.mimetype == "text/csv" && file.fieldname === "test_doc") {
        cb(null, true);
      } else {
        cb(null, false);
        return cb(new Error('Invalid upload: fieldname should be test_doc and .csv format '));
      }
    }
  });
发布评论

评论列表(0)

  1. 暂无评论