In app.js import multer
Import uuidv4 in case you want to generate uniqu universal id to name the images.
Define fileStorage and fileFilter
Middleware to store the image
In controller, use req.file to access the image file from the form. Save it's path to imageUrl in database, to access while displaying data.
Import uuidv4 in case you want to generate uniqu universal id to name the images.
const multer = require('multer');
const uuidv4 = require('uuid/v4');
Define fileStorage and fileFilter
const fileStorage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'images'); // 'images' is the storage folders
},
filename: (req, file, cb) => {
cb(null, uuidv4());
}
});
const fileFilter = (req, file, cb) => { // to save only image and not other files
if ((file.mimetype === 'image/png') ||
(file.mimetype === 'image/jpg') ||
(file.mimetype === 'image/jpeg')) {
cb(null, true);
} else {
cb(null, false);
}
};
Middleware to store the image
app.use(multer({ storage: fileStorage, fileFilter: fileFilter }).single('image'));
In controller, use req.file to access the image file from the form. Save it's path to imageUrl in database, to access while displaying data.
Comments
Post a Comment