Add - FileFilter.js
Pre-releaseSetting up the Express application:
const fileFilter = (req, file, cb) => {
if (file.mimetype.startsWith('image/') || file.mimetype === 'image/gif') {
cb(null, true);
} else {
req.fileValidationError = 'Only images and GIFs are allowed to be uploaded';
cb(null, false);
}
};
module.exports = fileFilter;
This code defines a middleware function named fileFilter which is used to filter uploaded files in a Node.js application using Express framework.
const fileFilter = (req, file, cb) => { ... }: Defines a function named fileFilter which accepts three parameters: req (the request object), file (the uploaded file), and cb (a callback function).
if (file.mimetype.startsWith('image/') || file.mimetype === 'image/gif') { ... }: This if block checks whether the MIME type of the uploaded file starts with 'image/' or it's 'image/gif'. The file.mimetype property provides the MIME type of the uploaded file. If the file is an image or a GIF, it calls the cb callback with null as the first argument and true as the second argument.
cb(null, true);: This is the callback that is called if the file meets the filtering criteria. null indicates that there is no error and true indicates that the file is accepted.
cb(null, false);: It calls the callback with null as the first argument (indicating no errors) and false as the second argument (indicating that the file does not meet the filtering criteria and thus should not be accepted).
module.exports = fileFilter;: Exports the fileFilter function so that it can be used in other files of the application.
In summary, this code defines a middleware function that checks if the uploaded file is an image or a GIF. If it is, it allows the request to proceed; otherwise, it sets an error message on the request and rejects the file.