我正在使用NodeJS,ExpressJS,mongoose,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
答案 0 :(得分:1)
我有同样的问题,我所做的是将几个选项传递给bodyParser对象。
app.use(express.bodyParser({ keepExtensions: true, uploadDir: __dirname + '/public/photos' }));
在我添加选项后,一切似乎都适合我。
答案 1 :(得分:0)
使用connect-multiparty并将其包含在路径文件中:
var multipart=require('connect-multiparty');
然后用作:
app.post('/uploads',multipart(),function(req,res){
// ...
});