我正在使用 NodeJS、ExpressJS、猫鼬、EJS。
上传表格:
<form method='post' enctype='multipart/form-data'>
<input type='text' name='photo[name]'/>
<input type='file' name='photo[image]'/>
<input type='submit' value='Upload'/>
</form>
模型:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/photo_app');
var schema = new mongoose.Schema({
name: String,
path: String
});
module.exports = mongoose.model('Photo', schema);
app.js
:
var app = express();
...
app.set('view engine', 'ejs');
app.use(express.logger('dev'));
app.use(express.bodyParser());
...
路线:
var Photo = require('../models/Photo');
var path = require('path');
var fs = require('fs');
var join = path.join;
exports.submit = function (dir) {
return function(req, res, next){
var img = req.files.photo.image;
var name = req.body.photo.name || img.name;
var path = join(dir, img.name);
fs.rename(img.path, path, function(err){
if (err)
return next(err);
Photo.create({
name: name,
path: img.name
}, function (err) {
if (err)
return next(err);
res.redirect('/');
});
});
};
};
尝试上传时的问题:
500 TypeError: Cannot read property 'photo' of undefined