Configuring Multer for User Avatar

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

Lecture 352:-  Configuring Multer for User Avatar

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.

41. File Upload

2 Comments

@niteshguptav63
niteshguptav63 Nov 17, 2024 at 1:39 PM

I am not able to access videos from second class and further. I have already completed first class

@niteshguptav63
niteshguptav63 Nov 16, 2024 at 10:56 AM

When will I get my course?

@admin79
admin79 Nov 17, 2024 at 1:29 PM

Now, Your query was resolved.

Frequently Asked Questions About Sciaku Courses & Services

Quick answers to common questions about our courses, quizzes, and learning platform

Didn't find what you're looking for?

help_center Contact Support