Utilizing [Multer][1] as middleware for handling multipart form data, I am taking advantage of the configuration options it provides through diskStorage
. This feature allows for error checking and control over file uploads within Multer.
The structure of my Express route is as follows:
expressRouter.post(['/create'],
MulterUpload.single("FileToUpload"), // If an error occurs here, Express will return it to the user
async function(req, res) {
// Process form text fields in req.body here
});
MulterUpload.single()
directs the file input field named "FileToUpload" for processing:
const MulterUpload = multer({
storage: MulterStorage
)}
const MulterStorage = multer.diskStorage({
destination: async function (req, file, cb) {
try {
if ("postID" in req.body && req.body.postID != null && req.body.postID.toString().length) {
const Result = await api.verifyPost(req.body.postID)
if (Result[0].postverified == false) {
const Err = new Error("That is not your post!");
Err.code = "ILLEGAL_OPERATION";
Err.status = 403;
throw(Err); // Unauthorized upload attempt
} else {
cb(null, '/tmp/my-uploads') // Allowed upload
}
}
} catch (err) {
// How can I send this error back to Express for returning it to the user? The error remains unresolved due to the use of async/await.
}
}
,
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now())
}
})
I'm faced with the challenge of figuring out how to relay the error from MulterStorage
back to Express, which would then present it to the browser/user as an error message.
[1]: https://www.npmjs.com/package/multer