admin管理员组

文章数量:1429560

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

本文标签: javascriptMulter validation with joiStack Overflow