Node.js Multer文件上传错误

时间:2015-12-02 07:29:51

标签: node.js multer

我收到了mainimage的未定义错误 任何人都可以帮我解决这个错误 事情是图像上传并从时间戳重命名 但它没有工作请帮助

这是app.js route

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var expressValidator = require('express-validator');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var bodyParser = require('body-parser');
var mongo = require('mongodb');
var db = require('monk')('localhost/nodeblog');
var multer = require('multer');
var flash = require('connect-flash');

var routes = require('./routes/index');
var posts = require('./routes/posts');
var categories = require('./routes/categories');


    var app = express();

app.locals.moment = require('moment');

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// Handle File Uploads
app.use(multer({dest:'./public/images/uploads'}).single('mainimage'));

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

// Handle Express Sessions
app.use(session({
  secret:'secret',
  saveUninitialized:true,
  resave:true
}));

// Express Validator
app.use(expressValidator({
  errorFormatter: function(param, msg, value) {
      var namespace = param.split('.')
      , root    = namespace.shift()
      , formParam = root;

    while(namespace.length) {
      formParam += '[' + namespace.shift() + ']';
    }
    return {
      param : formParam,
      msg   : msg,
      value : value
    };
  }
}));

app.use(express.static(path.join(__dirname, 'public')));

// Connect-flash
app.use(flash());
 app.use(function (req, res, next) {
  res.locals.messages = require('express-messages')(req, res);
  next();
});

// Make our database accessible to our router
app.use(function(req, res, next){
  req.db = db;
  next();
})

app.use('/', routes);
app.use('/posts', posts);
app.use('/categories', categories);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});


module.exports = app;

这是post.js路线代码

var express = require('express');
var router = express.Router();
var mongo = require('mongodb');
var db = require('monk')('localhost/nodeblog');

router.get('/add', function(req, res, next){
    var categories = db.get('categories');

    categories.find({},{},function(err, categories){
        // console.log(categories);

        res.render('addpost',{
        "title":"Add Post",
        "categories": categories
        });
    });
});

router.post('/add', function(req, res, next){
    // GET FORM VALUES
    var title       = req.body.title;
    var category    = req.body.category;
    var body        = req.body.body;
    var author      = req.body.author;
    var date        = new Date();

    console.log(req.file);
    console.log(req.file.mainimage)
    if(req.file.mainimage){
        var mainImageOriginalName   = req.file.mainimage.originalname;
        var mainImageName           = req.file.mainimage.filename;
        var mainImageMime           = req.file.mainimage.mimetype;
        var mainImagePath           = req.file.mainimage.path;
        var mainImageExt            = req.file.mainimage.extension;
        var mainImageSize           = req.file.mainimage.size;
        // console.log(mainImageName);
    } else{
        var mainImageName = 'noimage.png';
        console.log(mainImageName);
    }

    // FORM VALIDATION
    req.checkBody('title','Title field is required').notEmpty();
    req.checkBody('body','Body field is required');

    // Check Errors
    var errors = req.validationErrors();

    if(errors){
        res.render('addpost',{
            "errors":errors,
            "title":title,
            "body":body
        });
    } else {
        var posts = db.get('posts');

        // SUBMIT TO DB
        posts.insert({
            "title":title,
            "body":body,
            "category":category,
            "date":date,
            "author":author,
            "mainimage":mainImageName
        }, function(err, post){
            if(err){
                res.send('There is an issue submiting the post');
            } else {
                req.flash('Success','Post submitted');
                res.location('/');
                res.redirect('/');
            }
        });
    }
});

module.exports = router;

这是addpost.jade文件

extends layout

block content
    h1=title
    ul.errors
        if errors
            each error, i in errors
                li.alert.alert-danger #{error.msg}
    form(method='post', action='/posts/add', enctype="multipart/form-data")
        .form-group
            label Title:
            input.form-control(name='title', type='text')
        .form-group
            label Category
            select.form-control(name='category')
                each category, i in categories
                    option(value='#{category.title}') #{category.title}
        .form-group
            label Body
            textarea.form-control(name=body, id='body')
        .form-group
            label Main Image:
            input.form-control(name='mainimage',type='file')
        .form-group
            label Author:
            select.form-control(name='author')
                option(value='Ankit Baid') Ankit Baid
                option(value='John Doe') John Doe
        input.btn.btn-default(name='submit' type='submit', value='Save')
    script(src='/ckeditor/ckeditor.js')
    script
        | CKEDITOR.replace('body');

2 个答案:

答案 0 :(得分:0)

您需要删除刚才需要mainimage的属性req.file

if(req.file){
    var mainImageOriginalName   = req.file.originalname;
    var mainImageName           = req.file.filename;
    var mainImageMime           = req.file.mimetype;
    var mainImagePath           = req.file.path;
    var mainImageExt            = req.file.extension;
    var mainImageSize           = req.file.size;
    // console.log(mainImageName);
} else{
    var mainImageName = 'noimage.png';
    console.log(mainImageName);
}

答案 1 :(得分:0)

您是否正在使用Udemy Node项目系列?您的代码看起来与我的相似,我也坚持使用multer文件上传。你在上传目录中看到文件了吗?

上传目录中有文件供我使用。但是当我检查我的mongodb时,图像部分是空白的。