Supez38
Supez38

Reputation: 349

Multer validation with joi

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

Upvotes: 1

Views: 10795

Answers (1)

jcoleau
jcoleau

Reputation: 1200

You can use the fileFilter method to validate file types in Multer. The fileFilter method is a built-in method which comes 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 '));
      }
    }
  });

Upvotes: 2

Related Questions