Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

307
Vistas
can't get file property using Multer

I'm trying to upload an image from my form using Multer, when I insert the image everything works fine But when there is no image chosen I got an error.

  • Here is multer config all uploaded images are stored in public/images/uploads:
//handle file upload

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'public/images/uploads/')
  },
  filename: function (req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now()+ '.jpg')
  }
});
var upload = multer({ storage: storage })

Now I want to get back the value of mainImageName but when I don't insert any image an error occurs cannot get property filename of undefined.

  • Here is the rest :

    //Submit new post
    router.post('/add', upload.single('mainimage'), function(req, res, next) {
    var title = req.body.title;
    var category = req.body.category;
    var body = req.body.body;
    var author = req.body.author;
    var date = new Date();
    
    if(req.file && req.file.mainimage){
    
        var mainImageName = req.file.filename;
        var mainImageMime = req.file.mainimage.mimetype;
        var mainImagePath = req.file.mainimage.path;
        var mainImageSize = req.file.mainimage.size;
    
    }else{
    
        //if there was no image uploaded!!
        //noimage.png should be placed in public/images/uploads
        mainImageName = 'noimage.png';
    }
    
    console.log(mainImageName); //always returns noimage.png !!
    
    //form validation
    req.checkBody('title', 'You forgot the title').notEmpty();
    req.checkBody('body', 'Please fill in the body').notEmpty();
    
    //check errors
    var errors = req.validationErrors();
    
    if(errors){
    

    var mycategories = []; var categories = db.get('categories'); categories.find({}, {}, function(err, categories) {

        for (i=0; i<categories.length; i++) {
              mycategories[i] = categories[i];
            }
     });
    res.render('addpost', {
            'pageTitle': 'Add Post',
            'errors': errors,
            'title': title,
            'body': body,
            'categories': mycategories
    
        });
    
    } else{
            var posts = db.get('posts');
            //submit Post
            posts.insert({   "title": title, 
                             "body": body,
                             "category": category,
                             "date": date,
                             "author": author,
                             "mainimage": mainImageName 
    
                     }, function(err, post) {
                if (err){
            res.send('There was an issue submitting the post.')
             } else {
                req.flash('success_msg', 'Post Submitted');
                res.location('/');
                res.redirect('/');
             }
             });
    }
    

    });

about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

I found the problem, the condition if(req.file && req.file.mainimage) was never met because req.file.mainimage is always undefined so I simply changed it to if(req.file) and it worked fine .

This is how it should look like:

if(req.file){

    var mainImageName = req.file.filename;
    var mainImageMime = req.file.mimetype;
    var mainImagePath = req.file.path;
    var mainImageSize = req.file.size;

}else{

    //if there was no image uploaded!!
    //noimage.png should be placed in public/images/uploads
    mainImageName = 'noimage.png';
}
about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda