I'm using multer for the first time and I noticed the image is always uploaded.
Now my problem is that I would like to do some data validation on the body of the request with Joi, then move the file in the appropriate folder if the data validation is a success.
Is it possible with Multer and how would you achieve this ?
Or, is there a way to disable the automatic upload with Multer and move the file manually once the data validation is done ?
Thanks a lot for your help.
There are multiple ways to do this. You could use a custom middleware doing validation before Multer, or you could manage the validation within Multer directly. Here is an example using the default DiskStorage:
const storage = multer.diskStorage({
destination: function (req, file, cb) {
const valid = ...; // your validation logic
if (valid) cb(null, '/tmp/my-uploads');
else cb(new Error('Validation failed.'));
},
});
const upload = multer({ storage: storage });
If you need more control, you can use MemoryStorage:
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });
app.post('/xyz', upload.single('file'), (req, res) => {
// because of memoryStorage, the file will be available in a buffer
// do your validation logic here, and when you are happy write the buffer to the disk
});
Read more about storage in the docs.