Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

304
Views
no se puede obtener la propiedad del archivo usando Multer

Estoy tratando de cargar una imagen desde mi formulario usando Multer , cuando inserto la imagen todo funciona bien, pero cuando no hay una imagen elegida, aparece un error.

  • Aquí está la configuración de multer, todas las imágenes cargadas se almacenan en 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 })

Ahora quiero recuperar el valor de mainImageName, pero cuando no inserto ninguna imagen, se produce un error cannot get property filename of undefined.

  • Aquí está el resto:

     //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 miscategorias = []; var categorías = db.get('categorías'); categorías.find({}, {}, función(err, categorías) {

     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 answers
Answer question

0

Encontré el problema, la condición if(req.file && req.file.mainimage) nunca se cumplió porque req.file.mainimage siempre está indefinida, así que simplemente la cambié a if(req.file) y funcionó bien.

Así es como debería verse:

 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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!