Search code examples
javascriptnode.jsexpressmulter

Get image path with Multer Express Nodejs


I am using Multer to save images but I need to get the path of the image to save it to MongoDB. I am trying to get the path with req.file but it always tells me on the console that it is undefined.

this is my route:

import { Router } from 'express';
import { check, validationResult } from 'express-validator';

const multer  = require('multer');

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
      cb(null, 'uploads/products')
    },
    filename: function (req, file, cb) {
      cb(null, new Date().toISOString().replace(/:/g, '-') + file.originalname)
    }
  });

const fileFilter = (req, file, cb) => {
    // reject a file

    if (file.mimetype === 'image/jpeg' ||file.mimetype === 'image/png') {
        cb(null, true);                
    } else {
        cb(null, false); 
        //cb(new Error('I don\'t have a clue!'))       
    }
}
  
const upload = multer(
    { storage: storage, 
    limits:{
        fileSize: 1024 * 1024 
    },
    fileFilter: fileFilter
});

let router = Router();

router.post('/', upload.single('img'),
    newProduct
);

And in the new Product controller I am trying to read the req.file but the console tells me that it is undefined:

Controller:


import { Product } from '../models'

let newProduct = async (req, res = response ) => {

     console.log('file ' + req.file); //UNDEFINED

    try {

        let { status, user, ...body } = req.body;


        let productDB = await Product.findOne ( { 'name': body.name } );
    
        if (productDB) {
    
            return res.status(400).json({
            
                msg:`El producto ${ productDB.name } ya existe`
            })
        }
    
        let data = { 
            ...body, 
            name: body.name, 
            user: req.user._id 
        }
    
        let product = new Product( data );
    
        await product.save();
    
        res.status(200).json( product );

    } catch (error) {

        return res.status(400).json({     
            error
        });   
    }
}


Console:

console

Thanks for your help.


Solution

  • you can try to do this in filename instead:

    filename: function (req, file, cb) {
      req.imageName = new Date().toISOString().replace(/:/g, '-') + file.originalname
      cb(null, req.imageName)
    }
    

    then there:

    console.log('file ' + req.file); //UNDEFINED
    //you can get imageName instead
    console.log('imageName',req.imageName)
    //if you want url to store in database you can do this 
    //supposing your have images directory in root of your node server
    const url = `${req.protocol}://${req.get('host')}/images/${req.body.image}`