Search code examples
node.jsmongodbimageexpressmulter

Multer Filename Of Undefined


I am coding a website just like blog which we can add pictures and articles. I am using multer, mongodb and multer. But I am getting a error that says

TypeError: Cannot read property 'filename' of undefined at C:\Users\agul\Desktop\NODEJS\veritabanı\routes\articles.js:58:33 ...

So that probably due to it cannot finding that filenme property I cannot upload my images. But I couldnt understand why it doesnt work.

Here is my codes:

This is my article.js

  const express = require('express');
const router = express.Router();
const multer = require('multer');

// Article Model
let Article = require('../models/article');
// User Model
let User = require('../models/user');

router.get('/sonuc', function(req, res){
  if(req.query.search) {
    const regex = new RegExp(escapeRegex(req.query.search), 'gi');
    Article.find({"title": regex}, function(err, articles) {
        if(err) {
            console.log(err);
        } else {
           res.render("sonuc", { 
             articles: articles 
            });
        }
    });
  }
});

function escapeRegex(text) {
  return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
};

// Add Route
router.get('/add', ensureAuthenticated, function(req, res){

  res.render('add_article', {
    title:'Add Article'
  });
});

const upload = multer({dest: __dirname + '/public/uploadss'});

// Add Submit POST Route
router.post('/add',upload.single('img'),  function(req, res){

  req.checkBody('title','Title is required').notEmpty();
  //req.checkBody('author','Author is required').notEmpty();
  req.checkBody('body','Body is required').notEmpty();

  // Get Errors
  let errors = req.validationErrors();

  if(errors){
    res.render('add_article', {
      title:'Add Article',
      errors:errors
    });
  } else {
var article = new Article({
    title: req.body.title,
    author: req.user._id,
    img: '/uploads/' + req.file.filename,
    body: req.body.body,
   });

    article.save(function(err){
      if(err){
        console.log(err);
        return;
      } else {
        res.render('add_article', {
        });
      }
    });
  }
});

// Load Edit Form
router.get('/edit/:id', ensureAuthenticated, function(req, res){
  Article.findById(req.params.id, function(err, article){
    /*if(article.author != req.user._id){
      req.flash('danger', 'Not Authorized');
      return res.redirect('/');
    }*/
    res.render('edit_article', {
      title:'Edit Article',
      article:article
    });
  });
});

// Update Submit POST Route
router.post('/edit/:id', function(req, res){
  let article = {};
  article.title = req.body.title;
  article.author = req.body.author;
  article.body = req.body.body;

  let query = {_id:req.params.id}

  Article.update(query, article, function(err){
    if(err){
      console.log(err);
      return;
    } else {
      req.flash('success', 'Article Updated');
      res.redirect('/');
    }
  });
});

// Delete Article
router.delete('/:id', function(req, res){
  if(!req.user._id){
    res.status(500).send();
  }

  let query = {_id:req.params.id}

  Article.findById(req.params.id, function(err, article){
    if(article.author != req.user._id){
      res.status(500).send();
    } else {
      Article.remove(query, function(err){
        if(err){
          console.log(err);
        }
        res.send('Success');
      });
    }
  });
});

// Get Single Article
router.get('/:id', function(req, res){

  Article.findById(req.params.id, function(err, article){
    //User.findById(article.author, function(err, user){
      res.render('article', {
        article:article,
        //author: user.name
      });
    });
  });
//});

// Access Control
function ensureAuthenticated(req, res, next){
  if(req.isAuthenticated()){
    return next();
  } else {
    req.flash('danger', 'Please login');
    res.redirect('/users/login');
  }
}
module.exports = router;

Also I have made up a mongoose model of img and articles at the same time. Everything seems correct but I couldnt understand where I make my mistake. Can you help ? If you can I really appreciate it. I have already created a folder named uploads and I direct the filnemane as /uploads but it doesnt work.

NOTE: THİS IS MY add_article.pug file. extends layout

block content
  h1 #{title}
  form(method='POST', action='/articles/add')
    #form-group
      label Title:
      input.form-control(name='title', type='text')
      #form-group
      label Author:
      input.form-control(name='author', type='text')
    #form-group
      label Body:
      textarea.form-control(name='body')
    .file-field.input-field(method="post", enctype="multipart/form-data")
      .btn.grey
        label File
        input(name='img', enctype = "multipart/form-data", type='file')
    br
    input.btn.btn-primary(type='submit',value='Submit')

This is my article.pug file

extends layout

block content
  br
  h1= article.title
  //h5 Written by #{author}
  p= article.body
  img(src='{article.img}', alt='img')




  hr
  if user
    if user.id ==article.author
      a.btn.btn-default(href='/articles/edit/'+article._id) Edit 
      a.btn.btn-danger.delete-article(href='#',data-id=article._id) Delete

The issue of filename of undefined is already solved but now I cannot represent my img to my article page. Can you please help me to solve this problem ?


Solution

  • you need to add

    enctype = "multipart/form-data" 
    

    in the form tag

    change your current code

      form(method='POST', action='/articles/add')
    
    

    into

      form(method='POST', action='/articles/add', enctype = "multipart/form-data")
    
    

    and remove from input file

    current

    .file-field.input-field(method="post" , enctype="multipart/form-data")
          .btn.grey
            label File
            input(name='img', enctype = "multipart/form-data", type='file')
    

    change into

    .file-field.input-field(method="post")
          .btn.grey
            label File
            input(name='img', type='file')
    

    reference : https://www.npmjs.com/package/multer (see the Basic Usage)

    =====

    to serve the file for use / call in the html, you need to route it from your express

    example : since your upload path is located at /public/uploadss

    and your article.js need to add code something like this

    router.use(express.static('public/uploadss'))
    

    TAKE NOTE : your upload folder is uploadss instead of uploads

    then for testing, you can open your browser with the url and check if its valid or not

    http://localhost:PORT/filename.jpg

    you can also create virtual path prefix

    router.use('/static', express.static('public/uploadss'))
    

    so you can access it something like http://localhost:PORT/static/filename.jpg

    reference : https://expressjs.com/en/starter/static-files.html