无法读取未定义的multer的属性

时间:2016-04-01 02:50:59

标签: node.js express pug

我正在为学习节点js express进行用户登录/注册。但我在上传文件时遇到问题,因为当我提交表单时,控制台说不能读取未定义的属性'profileimage'。

我认为问题是我没有正确使用multer模块,但正如我所说,我只是一个节点的新手。

我非常感谢您的帮助,这是代码

app.js

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 passport=require('passport');
var localStrategy=require('passport-local').strategy;
var bodyParser = require('body-parser');
var multer=require('multer');
var flash =require('connect-flash');
var mongo= require('mongodb');
var mongoose=require('mongoose');
var db=mongoose.connection;
var upload = multer({ dest: 'uploads/' });
var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

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

//Handle file uploads
app.use(upload.single('file'));

// 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 }));

//handle epress session
app.use(session({
  secret:'secret',
  saveUninitialized:true,
  resave:true

}));
//passport
app.use(passport.initialize());
app.use(passport.session());

//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(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(flash());
app.use(function (req, res, next) {
  res.locals.messages = require('express-messages')(req, res);
  next();
});
app.use('/', routes);
app.use('/users', users);


// 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;

这是使用multer的代码,问题出在if(req.file.profileimage)条件

router.post('/register',function(req,res,next){
//recuperar datos del formulario
    var name        = req.body.name;
    var email       = req.body.email;
    var username    =req.body.username;
    var password    =req.body.password;
    var password2   =req.body.password2;

//revisar input de imagen
if(req.file.profileimage){

        console.log('Uploading File..');
        var profileimageOriginalName    =req.files.profileimage.originalname;
        var profileImageName            =req.files.profileimage.name;
        var profileImageMime            =req.files.profileimage.mimeType;
        var profileImagePath            =req.files.profileimage.path;
        var profileImageExt             =req.files.profileimage.extension;
        var profileImageSize            =req.files.profileimage.size;

    }else{
    //set defaut
    var profileImageName='noimage.png';

    }

    //validacion forma
    req.checkBody('name','Name field is required').notEmpty();
    req.checkBody('email','Email field is required').notEmpty();
    req.checkBody('email','mail not valid').isEmail();
    req.checkBody('username','Userame field is required').notEmpty();
    req.checkBody('password','Password field is required').notEmpty();
    req.checkBody('password2','Passwords dont match').equals(req.body.passowrd);
    //revisando errores
    var errors= req.validationErrors();

    if(errors){
        res.render('register',{
            errors:errors,
            name:name,
            email:email,
            username:username,
            password:password,
            password2:password2
        });
    }else{//cuando los datos son válidos
        var newUser= new User({
            errors:errors,
            name:mame,
            email:email,
            username:username,
            password:password,
            profileimage:profileImageName
        });
        User.createUser(newUser,function(err,user){

            if(err) throw err;
            console.log(user);
        });

        req.flash('success','your are redy');
        res.location('/');
        res.redirect('/');
    }
});

这是玉石形式

form(method='post',action='/users/register',enctype='multipart/form-data')
    .form-group
        label Name
        input.form-control(name='name', type='text',placeholder='Enter Name')
    .form-group
        label Email
        input.form-control(name='email', type='email',placeholder='Enter Email')
    .form-group
        label Username
        input.form-control(name='username', type='text',placeholder='Username')
    .form-group
        label Password
        input.form-control(name='password', type='password',placeholder='Enter Password')
    .form-group
        label Confirm Password
        input.form-control(name='password2', type='password',placeholder='Confirm Password')
    .form-group
        label Profile Image
        input.form-control(name='profileimage', type='file')
    input.btn.btn-default(name='submit', type='submit',value='Register')

正如我所说,我确定问题是闷热,但我不知道如何解决它,因为jade文件和users.js中的name属性是相同的。我还检查了Multer文档,但我自己无法修复它。

感谢你的帮助:)

1 个答案:

答案 0 :(得分:2)

当您使用upload.single()时,由于输入字段名称(req.file)已知(已传递给{{1 }})。这意味着您还需要将文件字段req.file.profileimage属性从profileimage更改为upload.single(),或更改传递给name的名称。

我还应该补充说,multer中间件通常是在路由处理程序级别添加的,因为字段名称通常会有所不同。因此,要以这种方式解析请求,您将删除profileimage并从以下位置更改路由处理程序行:

file

为:

upload.single()