If you have any query feel free to chat us!
Happy Coding! Happy Learning!
To configure Multer for user avatar, we need to create an instance of Multer and pass in an options object specifying the destination directory and file name.
Here's an example of how we can configure Multer for user avatar:
javascriptCopy code
const multer = require('multer');
const path = require('path');
// Set storage engine for user avatar
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public/uploads/avatars');
},
filename: function (req, file, cb) {
cb(null, Date.now() + path.extname(file.originalname));
}
});
// Init upload
const upload = multer({
storage: storage,
limits: { fileSize: 1000000 }, // max file size 1MB
fileFilter: function (req, file, cb) {
checkFileType(file, cb);
}
}).single('avatar');
// Check file type
function checkFileType(file, cb) {
// Allowed file extensions
const filetypes = /jpeg|jpg|png|gif/;
// Check file extension
const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
// Check mime type
const mimetype = filetypes.test(file.mimetype);
if (mimetype && extname) {
return cb(null, true);
} else {
cb('Error: Images only!');
}
}
In the above code, we're setting the storage engine for user avatar by creating a new instance of Multer's diskStorage
class. We're specifying the destination directory for storing the uploaded avatar using the destination
property and the filename
property is used to generate a unique name for the uploaded file by appending a timestamp to the original file name using the Date.now()
method.
Next, we're setting upload limits for file size and file type validation using the limits
and fileFilter
properties respectively. In the fileFilter
function, we're checking if the uploaded file is an image with allowed file extensions such as jpeg, jpg, png, and gif.
Finally, we're creating a single file upload middleware by calling the single
method and passing the field name of the file input as an argument. This middleware can be used in our routes to handle file uploads for user avatar.
When will I get my course?
Now, Your query was resolved.
Quick answers to common questions about our courses, quizzes, and learning platform
I am not able to access videos from second class and further. I have already completed first class