I have a problem with multer middleware. I created the middleware and set the static express files to the images folder
app.use('/images', express.static(path.join(__dirname, 'images')));
The multer middleware
const multer = require('multer');
const MIME_TYPES = {
'image/jpg': 'jpg',
'image/jpeg': 'jpg',
'image/png': 'png'
};
const storage = multer.diskStorage({
destination: (req, file, callback) => {
callback(null, 'images');
},
filename: (req, file, callback) => {
const name = file.originalname.split(' ').join('_');
const extension = MIME_TYPES[file.mimetype];
callback(null, name + Date.now() + '.' + extension);
}
});
module.exports = multer({storage: storage}).single('image');
After this, I attached the middleware to the router:
router.post('/add-avatar', multer, addAvatar);
The next step is the problem. The middleware does not executing the function at all. I am trying everything...
exports.add = async (req, res, next) => {
try {
let url = req.protocol + '://' + req.get('host');
let imageLink = req.file ? url + '/images/' + req.file.filename : '';
res.send(imageLink);
}
catch (error) {
console.log(error);
}
}
I tried to delete the multer middleware and the requests goes thought. I also tried to upload file with postman. But the request is left in pending..
I dont know what im doing wrong...
Try the code below instead:
const multer = require("multer");
const upload = multer({
dest: "images/",
limits: { fieldSize: 25 * 1024 * 1024 },
});
router.post("/add-avatar", upload.single("image"), async (req, res) => {
let url = req.protocol + '://' + req.get('host');
let imageLink = req.file ? url + '/images/' + req.file.filename : '';
res.send(imageLink);
});
module.exports = router;