File type validations in expressjs/multer
expressjs/multer is a great Node.js middleware which handles the file upload with validations like:
- Number of files to be uploaded
- Size of the files
- File extensions
Sometimes we want to validate the file extension, and also ensure the file format is indeed matching its extension. To achieve this, we can utilise sindresorhus/file-type
const express = require('express');
const multer = require('multer');
const fileType = require('file-type');
const app = new express();
const accepted_extensions = ['jpg', 'png', 'gif'];
const upload = multer({
limits: {
fileSize: 5 * 1024 * 1024, // 5 MB upload limit
files: 1 // 1 file
},
fileFilter: (req, file, cb) => {
// if the file extension is in our accepted list
if (accepted_extensions.some(ext => file.originalname.endsWith("." + ext))) {
return cb(null, true);
}
// otherwise, return error
return cb(new Error('Only ' + accepted_extensions.join(", ") + ' files are allowed!'));
}
});
/**
* Middleware for validating file format
*/
function validate_format(req, res, next) {
// For MemoryStorage, validate the format using `req.file.buffer`
// For DiskStorage, validate the format using `fs.readFile(req.file.path)` from Node.js File System Module
let mime = fileType(req.file.buffer);
// if can't be determined or format not accepted
if(!mime || !accepted_extensions.includes(mime.ext))
return next(new Error('The uploaded file is not in ' + accepted_extensions.join(", ") + ' format!'));
next();
}
app.post("/",
// First middleware, validate number of files (one file) / size (5MB) / extension ('jpg', 'png', 'gif')
upload.single("file_field_name"),
// Second middleware, validate file format ('jpg', 'png', 'gif')
validate_format,
function(req, res, next) {
// Passed validations, do something with the file (`req.file`)
// ...
res.send("file uploaded");
}
);
app.listen(3000, () => {
console.log("Express listening on port 3000");
});