上传空文件时无法读取未定义的属性

时间:2015-09-26 09:47:20

标签: javascript node.js express pug

我正在使用Node.js(v0.10.25)和Express(4.13.1)并使用jade而不是HTML。我有一个注册表单,用户可以在其中注册并上传个人资料图片。

一切正常,除非我上传空图像,然后我收到以下错误:

无法读取未定义的属性'profileimage'

APP.JS

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var methodOverride = require('method-override');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var multer = require('multer');
var flash = require('connect-flash');
var expressValidator = require('express-validator');
var mongo = require('mongodb');
var mongoose = require('mongoose');
var db = mongoose.connection;


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(multer({dest:'./uploads/'}).single('singleInputFileName'));

// 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 Express Sessions
app.use(session({
        secret: 'secret',
        saveUninitialized: true,
        resave: true
        }));


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

//Vallidator
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')));


// Flash
app.use(flash());

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;

user.js的

var express = require('express');
var router = express.Router();

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

router.get('/Registreren', function(req, res, next) {
  res.render('Registration', { title: 'Registreren' });
});

router.get('/Aanmelden', function(req, res, next) {
  res.render('Aanmelden', { title: 'Aanmelden' });
});

router.post('/Registreren', function(req, res, next){
    // Get form value
    console.log('Bericht in behandeling ...')
    var username = req.body.username;
    var email = req.body.email;
    var password = req.body.password;
    var password_confirm = req.body.password_confirm;

    console.log('username: ' + username);
    console.log('email: ' + email);
    console.log('password: ' + password);
    console.log('password_confirm: ' + password_confirm);
    console.log('FIRST TEST: ' + JSON.stringify(req.files));
    console.log('SECOND TEST: ' + req.files.profileimage);

    // Check for image field
    if (req.files.profileimage){
        console.log('Uploading file....');

        //File Info 
        var profileImageOrginalName     = req.files.profileimage.orginalname;
        var profileImageName            = req.files.profileimage.name;
        var profileImageMimetype        = req.files.profileimage.mimetype;
        var profileImagePath            = req.files.profileimage.path;
        var profileImageExt             = req.files.profileimage.extension;
        var profileImageSize            = req.files.profileimage.size;
    } else{
         console.log('profileImageFile not found....');
        // Set default image
        var profileImageName = 'noimage.png';
    }

    // Form validation
        req.checkbody('username','Gebruikersnaam is verplicht').notEmpty();
        req.checkbody('email','email is verplicht').notEmpty();
        req.checkbody('email','email is niet geldig').isEmail();
        req.checkbody('username','Gebruikersnaam is verplicht').notEmpty();
        req.checkbody('password','Gebruikersnaam is verplicht').notEmpty();
        req.checkbody('password_confirm','Wachtwoorden zijn niet gelijk').equals(req.body.password);
        req.checkbody('username','Gebruikersnaam is verplicht').notEmpty();

    // Error handling
    console.log('Error handling....');
    var errors = req.valdidationErrors();

    if (errors){
        console.log('Form Errors....');
        res.render('Registreren',{
            errors: errors,
            username: username,
            email: email,
            password: password,
            password_confirm: password_confirm
        });
    }else {
          console.log('No Form Errors....');
        var newUser = new User({
               username: username,
               email: email,
               password: password,
               profileimage: profileImageName })

        // Create User
//        User.createUser(newUser, function(err,user){
//            if(err) throw err;
//            console.log(user);
//        });

    // Succes message
    req.flash('succes','Je bent succesvol aangemedld');
    res.location('/');
    res.redirect('/');
    }

    });



module.exports = router;

我已阅读并尝试过的内容:

  1. https://github.com/danialfarid/ng-file-upload/issues/185

  2. nodejs and express error when uploading file, "cannot read property of undefined"

  3. TypeError: Cannot read property 'image' of undefined

  4. 在USER.JS上,它在第一次测试时给出结果“未实现”,在第二次测试时它完全失败。另外,我在

    中的else语句中获得了nog cosole.log
    if (req.files.profileimage){
            console.log('Uploading file....');
    
            //File Info 
            var profileImageOrginalName     = req.files.profileimage.orginalname;
            var profileImageName            = req.files.profileimage.name;
            var profileImageMimetype        = req.files.profileimage.mimetype;
            var profileImagePath            = req.files.profileimage.path;
            var profileImageExt             = req.files.profileimage.extension;
            var profileImageSize            = req.files.profileimage.size;
        } else{
             console.log('profileImageFile not found....');
            // Set default image
            var profileImageName = 'noimage.png';
        }
    

1 个答案:

答案 0 :(得分:8)

确保req.files存在或您将获得未定义的错误。即:

if (req.files && req.files.profileImage) {
  // only if there are files
} else {
  // You should see this now
}