In the code below, from the multer API, both the destination and filename options are anonymous functions. Both of these functions have an argument called cb. Are these callback functions defined in the multer module somewhere or am I supposed to supply them?
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, '/tmp/my-uploads')
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now())
}
})
var upload = multer({ storage: storage }
The answer is: yes cb is provided by multer. And yes, it's weird documentation says nothing about it.
This callback is a so called error-first function, thus when examining the req, or file you may decide, that user uploaded something wrong, pass new Error() as first argument, and it will be returned in response. Note though, that it will raise an unhandled exception in your app. So I prefer to always pass null and handle user input in the corresponding controller.
const storage = multer.diskStorage({
destination: function (req, file, cb) {
const error = file.mimetype === 'image/jpeg'
? null
: new Error('wrong file');
cb(error, '/if-no-error-upload-file-to-this-directory');
},
//same for filename
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With